正则表达式过滤数组javascript

时间:2021-05-19 23:06:37

标签: javascript reactjs

所以我有一个正则表达式:

<proxy enabled="true" preserveHostHeader="true" />

products 数组中的一个项目看起来像这样:

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

基本上,每当用户输入时,都会发送此关键字。我然后使用

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

我在这里遇到的问题是,如果产品名称是“Men's Shirts”或“Women's Shirts”或任何包含 {'} 的东西,过滤器将不再起作用。 知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您清理了搜索文本,而不是项目名称。您也可以清理项目名称,以便它们使用相同的“允许字符”,从而更好地找到匹配项:

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);

答案 1 :(得分:0)

你的

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

将删除与该字符集不匹配的任何字符,导致正则表达式可能缺少字符。 Men's type into search 将产生 \bMens 正则表达式,这不是您所需要的。

匹配输入中的字母数字序列,并检查所有这些序列是否都包含在您正在查看的项目中。

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

虽然您可以使用正则表达式来实现相同的逻辑,但动态构造它会有点复杂。使用 .every 更简单、更直观。