比较字符串和数组的快速方法

时间:2018-08-29 04:40:15

标签: javascript typescript

我有一个名称很多的数组:{'John Doe', 'Peter Shark', ...}

现在我想比较和匹配一个字符串,例如'This is your turn John Doe, pls do it'并返回名称(如果数组包含该名称)。 该字符串可以是一个长文本。

我已经这样尝试过了,但是不起作用:

var searchStr = "This is your turn John Doe, pls do it"

var stringArray = ["John Doe", "Peter Shark"];

return (stringArray.indexOf(searchStr) > -1)

2 个答案:

答案 0 :(得分:10)

您需要进行另一种搜索-遍历stringArray并检查some中是否包含searchStr个名称:

var searchStr1 = "This is your turn John Doe, pls do it";
var stringArray = ["John Doe", "Peter Shark"];
console.log(stringArray.some(name => searchStr1.includes(name)));

var searchStr2 = "This is your turn Foo Bar, pls do it";
console.log(stringArray.some(name => searchStr2.includes(name)));

尽管some非常干净明了,但for循环比数组方法要快一些,尽管只有当您有成千上万个要迭代的项目时才重要:

var searchStr = "This is your turn John Doe, pls do it";
var stringArray = ["John Doe", "Peter Shark"];

const searchFor = stringArray => {
  for (let i = 0, { length } = stringArray; i < length; i++) {
    if (searchStr.includes(stringArray[i])) return true;
  }
  return false;
};

console.log(searchFor(["John Doe", "Peter Shark"]));
console.log(searchFor(["Foo Bar", "Peter Shark"]));

答案 1 :(得分:2)

正则表达式非常擅长快速查找内容。您可以提前准备正则表达式,然后在stringArray不变的情况下稍后再使用:

let searchStr = "This is your turn John Doe, pls do it"
let stringArray = ["John Doe", "Peter Shark"];

let nameMatcher = new RegExp(stringArray.map(
  // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
).join('|'));

console.log(searchStr.match(nameMatcher));