1

So I have a regex:

  const [keyword, setKeyword] = useState('')
  const pattern = new RegExp('\\b' + filterkeyword.replace(/[^a-zA-Z0-9 ]/g, ""), 'i')

An item in the products array would look something like this:

{
 name: 'Men's Shirts',
 price: 123,
 sale: 30,
 ...
}

basically, whenever a user types on an input, this keyword is being sent. I am then using

products.filter(x=> pattern.test(x.name)).map(product=> {return <Product />})

The issue I'm having here is that if the name of the product is "Men's Shirts" or "Women's Shirts" or anything that contains a {'}, the filter won't work anymore. Any idea how I can fix this issue?

0

2 Answers 2

2

You clean the search text, but not the item names. You could clean the item names as well, so they use the same "allowed characters", giving a better chance of finding matches:

const clean = text => text.replace(/[^a-zA-Z0-9 ]/g, "");
const products = [{ name: "Men's Shirts" }];

const getProducts = filterkeyword => {
  const pattern = new RegExp('\\b' + clean(filterkeyword), 'i');
  return products.filter(x => pattern.test(clean(x.name)));
}

console.log(getProducts("men's")[0]?.name);
console.log(getProducts("mens")[0]?.name);
console.log(getProducts("men🐱‍🐉s")[0]?.name);
console.log(getProducts("shoes")[0]?.name);
console.log(getProducts("shirts")[0]?.name);

Sign up to request clarification or add additional context in comments.

Comments

0

Your

filterkeyword.replace(/[^a-zA-Z0-9 ]/g, "")

will remove any characters not matching that character set, resulting in a regular expression that may be missing characters. Men's type into search will result in a \bMens regex, which is not what you need.

Match alphanumeric sequences in the input instead, and check that all of them are included in the item you're looking at.

const searchedWords = (filterkeyword.toLowerCase().match(/[a-z\d]/g) || []);
products.filter(
  prod => searchedWords.every(word => prod.name.toLowerCase().includes(word))
)

While you could use a regular expression to implement the same logic, it'd be a tiny bit convoluted to construct dynamically. Using .every is easier and more intuitive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.