我有两个字符串:
var first = "913 DE 6D 3T 222"
var second = "913 DE 3T 222"
我想检查 second
是否出现在 first
中,最好使用 regex
。问题是 indexOf
或 includes
返回 second
在 first
中不 ,这是错误的(只有 6D
是不同的):
first.indexOf(second)
-1
first.includes(second)
false
最佳答案
使用String#split
和 Array#every
方法。
var first = "913 DE 6D 3T 222";
var second = "913 DE 3T 222";
console.log(
second
// split the string by space
.split(' ')
// check all strings are contains in the first
.every(function(v) {
return first.indexOf(v) > -1;
// if you want exact word match then use regex with word
// boundary although you need to escape any symbols which
// have special meaning in regex but in your case I think all are
// alphanumeric char so which is not necessary
// return (new RegExp('\\b' + v + '\\b')).test(first);
})
)
仅供引用:对于较旧的浏览器,请检查 polyfill option of every
method .
关于javascript - 检查子字符串是否存在于另一个字符串中,正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40990886/