简体   繁体   English

正则表达式在数组中查找值

[英]RegExp to find value in the array

Here is my JavaScript with a RegExp which does not work, I cannot find the correct syntax:这是我的带有 RegExp 的 JavaScript,它不起作用,我找不到正确的语法:

var arr = ['111', '222|12', '333'];
new RegExp('\\b' + value + '\\b').test(arr);
value = '111'; //true
value = '222'; //true
value = '12'; //true

I need avoid numbers following a |我需要避免数字跟随| , meaning that a test with number 12 should return false. ,这意味着编号为12的测试应返回 false。 So values 111, 222 and 333 must yield true only.所以值 111、222 和 333 必须只产生 true。

I just know that the first \\\\b must be replaced with a syntax to avoid the |我只知道第一个\\\\b必须用语法替换以避免| character.特点。

You are passing an array to the test method, while it expects a string.您将一个数组传递给test方法,而它需要一个字符串。 So the array gets coerced to a comma separated string "111,222|23,333".所以数组被强制转换为逗号分隔的字符串“111,222|23,333”。 Obviously that makes your tests succeed, but you would also get a match with "111,222".显然,这会使您的测试成功,但您也会与“111,222”匹配。

Using a regular expression for this seems overkill.为此使用正则表达式似乎有点矫枉过正。 You can use split("|") to get rid of the part that follows a pipe symbol, and then just do an equality test on each remaining value.您可以使用split("|")摆脱管道符号后面的部分,然后对每个剩余值进行相等测试。 Use the some method to iterate until you get such a match:使用some方法进行迭代,直到获得这样的匹配:

 function isMatch(arr, value) { return arr.some(s => s.split('|')[0] === value); } var arr = ['111', '222|12', '333']; console.log(isMatch(arr, '111')); //true console.log(isMatch(arr, '222')); //true console.log(isMatch(arr, '333')); //true console.log(isMatch(arr, '12')); //false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM