如何将字符串与字符串数组匹配

时间:2019-03-05 08:41:09

标签: javascript arrays

我有一个包含字符串的数组

commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

我想匹配字符串

 var comment = "hello world ran"

我正在做的是

commentArray.words.find(words => {
    if (comment.toLowerCase().includes(words.toLowerCase())) {
      return true;
    }
  });

它给出true,因为“ random”包含“ ran”,但是我只希望匹配整个字符串而不是字符。

5 个答案:

答案 0 :(得分:2)

您可以这样做:

const commentArray = {
    "words": [ "xyz", "abc", "random", "sample" ] 
};

const comment = "hello world ran";
const commentArr = comment.split(' ');

commentArray.words.find(words => {
    if (commentArr.includes(words.toLowerCase())) {
        return true;
    }
});

答案 1 :(得分:1)

var commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

 var comment = "hello world random";
 var commentInWords = comment.split(" ");
 var res = commentArray.words.filter(words => {
    let a = _.includes(commentInWords,words.toLowerCase())
        if (a) {
          return true;
        }else{
          return false;
      }
 });

 console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 2 :(得分:1)

var commentArray ={ "words":[ "xyz", "abc", "random", "sample" ] };
var comment = "hello xyz";
var commentInWords = comment.split(" ");
 var res = commentArray.words.filter(words => {
   for(var i = 0; i <= commentInWords.length; i++){
    var a = (commentInWords[i] == words.toLowerCase());
        if (a) {
          return true;
        }
   }
 });

 console.log(res)

答案 3 :(得分:0)

1)将字符串“ comment”拆分为单词数组

2)对于注释中的每个单词,请尝试在“单词”数组中找到它。您可以使用类似的比较方法,但是当然需要与===而不是includes进行比较。

答案 4 :(得分:0)

commentArray.words.some(word =>〜comment.split(“”).indexOf(word))