2

I have a string var input = "Hello there, my name is Felix" and an array var names = ["John", "Bob", "Felix", "Alicia"]. How can I know if input contains one or multiple words of names ? Thanks. Edit: I'd like to know what word of input is in names

0poss
  • 153
  • 1
  • 8
  • 1
    Possible duplicate of [How to find an array of strings in a string?](https://stackoverflow.com/questions/40495372/how-to-find-an-array-of-strings-in-a-string) – Kevin B Jan 22 '19 at 19:57

3 Answers3

3

Using Array#filter and String#includes will get all the names included in your input.

const input = "Hello there, my name is Felix"
const names = ["John", "Bob", "Felix", "Alicia"]

const res = names.filter(n=>input.includes(n));

console.log(res);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

You have number of options here, the cleanest in my opinion is the following:

const namesInString = names.filter( name => input.contains(name) ) In this approach, filter iterates over the array and stores any given name in the resulting namesInString array, if the name was found in the array.

On an unrelated note, keep in my case sensitivity, so the complete solution should be: const namesInString = names.filter( name => input.toLowerCase().contains(name.toLowerCase()) )

I hope this helps.

Jacobdo
  • 1,681
  • 2
  • 18
  • 38
0

Another alternative could be using filter() with match(), creating a new Regular Expression on every iteration and setting the flag ignoreCase if you need it.

const input = "Hello there, my name is Felix";
const names = ["John", "Bob", "Felix", "Alicia", "hello"];

let res = names.filter(name => input.match(RegExp(name, "i")));
console.log("With ignore-case enabled: ", res);

res = names.filter(name => input.match(RegExp(name)));
console.log("Without ignore-case enabled: ", res);

However, if you don't mind to get the matches and only need to test is some of the string in the array appears on the input string, you could use a little faster approach using some().

const input1 = "Hello there, my name is Felix";
const input2 = "I don't have matches";
const names = ["John", "Bob", "Felix", "Alicia", "hello"];

const res1 = names.some(name => input1.match(RegExp(name, "i")));
console.log("Has coincidences on input1? ", res1);

const res2 = names.some(name => input2.match(RegExp(name, "i")));
console.log("Has coincidences on input2? ", res2);
Shidersz
  • 16,846
  • 2
  • 23
  • 48