Momen
Momen

Reputation: 512

Typescript or Javascript: searching for multiple words

const arr = ['hello', 'test', 'two words']

const string = 'this is two test words'

what i try to achieve is to check if this two words 'two words' in arr comes back in the string even if they are not behind each other. Also in any order but both words must be exist.

how can I achieve that?

Upvotes: 0

Views: 510

Answers (2)

Emeeus
Emeeus

Reputation: 5250

Here a possible approach using test() that returns true or false and new RegExp. But this does not cover if words are in different order.

const arr = ['hello', 'test', 'two words']

const string = 'this is two test words';

arr.forEach(o=>{

let r = new RegExp(o.replace(" ",".*"),"g");

console.log(r.test(string));

})

More powerful way. To check the words in any order we could compare two arrays using indexOf():

const arr = ['hello', 'test', 'two words']

const string = 'this is words two test';//<-- "words two" different order

var newarr2 = string.split(" ");

var newarr =  arr.map(o=>o.split(" "));

function flatten(arr) {
    return arr.reduce(function (flat, toFlatten) {
      return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
    }, []);
  }

  newarr = flatten(newarr);

  newarr.forEach(o=>{
      console.log(o+" ---> "+(newarr2.indexOf(o) != -1))
  })

Upvotes: 2

Georgy
Georgy

Reputation: 2462

const arr = ['hello', 'test', 'two words']
const string = 'this is two test words'

let regexpedArray = arr
  .map(w => new RegExp(w.replace(' ', '.*')))
  .forEach((val, i) => console.log(`${val.test(string)} for the value ${arr[i]}`))

The result would look like:

"false for the value hello"
"true for the value test"
"true for the value two words"

Upvotes: 2

Related Questions