打字稿或Javascript:搜索多个单词

时间:2018-08-24 14:39:33

标签: javascript arrays typescript

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

const string = 'this is two test words'

我试图实现的目的是检查arr中的两个单词“两个单​​词”是否回到字符串中,即使它们彼此之间不在彼此后面。同样,但两个词都必须存在。

我该如何实现?

2 个答案:

答案 0 :(得分: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]}`))

结果如下:

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

答案 1 :(得分:1)

这里有一种使用test()的方法,该方法返回 true false new RegExp但这并不涵盖单词顺序不同的情况

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

})

更强大的方法。要以任何顺序检查单词,我们可以使用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))
  })