如何将字符串与字符串数组匹配
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将字符串与字符串数组匹配相关的知识,希望对你有一定的参考价值。
我有包含字符串的数组
commentArray = "words":[ "xyz", "abc", "random", "sample" ]
我想匹配字符串
var comment = "hello world ran"
我正在做的是
commentArray.words.find(words =>
if (comment.toLowerCase().includes(words.toLowerCase()))
return true;
);
它给出了真实,因为“随机”包含“运行”,但只有匹配整个字符串而不是字符时我才想要真实。
答案
你可以这样做:
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;
);
另一答案
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>
另一答案
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)
另一答案
1)将字符串“comment”拆分为单词数组
2)对于评论中的每个单词,尝试在“单词”数组中找到它。您可以使用类似比较的东西,但当然需要与===
而不是includes
进行比较。
另一答案
commentArray.words.some(word => ~comment.split(“”)。indexOf(word))
以上是关于如何将字符串与字符串数组匹配的主要内容,如果未能解决你的问题,请参考以下文章