0

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?

1
  • Either split and look at each one or turn it into reg exp or do any other things. Commented Aug 24, 2018 at 14:41

2 Answers 2

2
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"
Sign up to request clarification or add additional context in comments.

1 Comment

The only bug in this code is that if a word in the string have the same character in the same order for example 'testjww', it give true back.
2

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

3 Comments

in the powerful way if i remove for example the word ' two' , it gives true back for the word 'words'. actually the both words must be exist.
@Momen in that case is better the first way, or Gregory answer. Or perform a check or a flag.
@Momen my way has one iteration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.