javascript - 检查子字符串是否存在于另一个字符串中,正则表达式

标签 javascript regex string

我有两个字符串:

var first = "913 DE 6D 3T 222"
var second = "913 DE 3T 222"

我想检查 second 是否出现在 first 中,最好使用 regex。问题是 indexOfincludes 返回 secondfirst ,这是错误的(只有 6D 是不同的):

first.indexOf(second)
-1

first.includes(second)
false

最佳答案

使用String#splitArray#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/

相关文章:

javascript - NodeJS : 'toString()' failed when require a large JSON file

javascript - 定义一个值在 1 到 100 之间的变量

javascript - 如何使用正则表达式从 javascript 中的日期字符串中删除时间戳

php - (string) 'hard-copy' 是字符串吗?

c - 我从堆中分配内存来存储一个字符,但它保存的是一个字符串

java - 从 JSP 调用外部 javascript 函数

javascript - node.js 是否在主线程中运行异步文件读取/写入?

regex - 将文本从一行复制到另一行

java - 使用正则表达式将缩写重新组合在一起

java - 将字符串添加到 ArrayList