[英]Filter array based on the keyword
I have an array:我有一个数组:
let array = [ 'Hello 1» (Foo_Test-Editable)', 'Hello 2» (Foo_Test-Editable)', 'Hello 3» (Foo_Test)', 'Foo_Test_4' ]; let searchKeyword = 'Foo_Test'; const result = array.filter(f => f.indexOf(searchKeyword) != -1); console.log(result);
Rules to find:查找规则:
Foo_Test
, not Foo_Test+...
plus some variations数组项应该只包含Foo_Test
,而不是Foo_Test+...
加上一些变化Desired result is:想要的结果是:
let result = [
'Hello 3» (Foo_Test)'
];
How to filter using the above rule?如何使用上述规则进行过滤?
If you can change the keyword to a regex...如果您可以将关键字更改为正则表达式...
let array = [ 'Hello 1» (Foo_Test-Editable)', 'Hello 2» (Foo_Test-Editable)', 'Hello 3» (Foo_Test)', 'Foo_Test_4' ]; let searchKeyword = /Foo_Test[^-|_]/; const result = array.filter(f => searchKeyword.test(f)); console.log(result);
Add the parentheses around "Foo_Test"
to distinguish it.在"Foo_Test"
周围添加括号以区分它。
let srch = "(Foo_Test)"
let arr = [ "Hello 1» (Foo_Test-Editable)", "Hello 2» (Foo_Test-Editable)", "Hello 3» (Foo_Test)", "FooText" ] let srch = "(Foo_Test)" const result = arr.filter( f => f.indexOf(srch)!= -1) console.log(result)
Actually your code is working , output was 3 array because all of them contained search value Foo_Test实际上您的代码正在运行,输出是 3 个数组,因为它们都包含搜索值Foo_Test
(3) ["Hello 1» (Foo_Test-Editable)", "Hello 2» (Foo_Test-Editable)", "Hello 3» (Foo_Test)"]
so add parentheses around (Foo_Test) to distinguish it from other, which will output specific value所以在(Foo_Test)周围添加括号以将其与其他人区分开来,这将输出特定值
(Foo_Test)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.