4

I have an array with a lot of names: {'John Doe', 'Peter Shark', ...}.

Now I would like to compare and match a string for e.g. 'This is your turn John Doe, pls do it' and return the name(s), if the array contains it. The string could be a long text.

I´ve tried it like this, but it do not work:

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

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

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

2 Answers 2

10

You need to search the other way around - iterate over stringArray and check if some of the names are contained in 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)));

While some is very clean and clear, for loops are slightly faster than array methods, though it should only matter if you have tens of thousands of items to iterate over:

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"]));

2

Regular expressions are pretty good at finding stuff quick. You can prepare the regexp ahead of time, then just reuse it later, if your stringArray stays the same:

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));

Not the answer you're looking for? Browse other questions tagged or ask your own question.