[英]Javascript Get Multiple Substrings Within One String
how to get multiple occurences of words in a string. 如何获得字符串中单词的多次出现。 I've tried multiple functions but with no success.
我尝试了多种功能,但没有成功。 I know I can get back the first true value using some() method as below.
我知道我可以使用some()方法获得第一个真实值,如下所示。
var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"];
function validateContentKeywords(content,keyword){
keyword.some(function(currentValue,index){
console.log(currentValue + " ");
return content.indexOf(currentValue) >= 0;
});
}
// Outputs --> Trap Samples
if(validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI",keyword_array)){
console.log("Matches");
}
// What I Want is --> Trap,Samples,MIDI,Loops
The above function only outputs 2 occurences and I want it to output all of the matching values at the same time such as --> Trap,Samples,MIDI,Loops. 上面的函数只输出2个事件,我希望它同时输出所有匹配值,例如-> Trap,Samples,MIDI,Loops。 Is there a way to get multiple occurences of words in a string at the same time?
有没有一种方法可以同时获取字符串中单词的多次出现?
UPDATED:: The solution that helped me out is below 更新::帮助我解决的解决方案如下
function Matches(value){
return "Beat Loops WAV Trap Samples Dog Cat MIDI".indexOf(value) !== -1;
}
var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"].filter(Matches);
document.write(keyword_array);
您似乎正在寻找可以返回匹配元素数组的filter
Array方法 ,而不是返回是否匹配的布尔值。
var keyword_array = ["Trap", "Samples", "WAV", "MIDI", "Loops"]; function validateContentKeywords(content, keyword) { var words = content.split(' '); //split the given string for (var i = 0; i < words.length; i++) { if (keyword.indexOf(words[i]) > -1) { //check if actually iterated word from string is in the provided keyword array document.write(words[i] + " "); //if it is, write it to the document }; } } validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI", keyword_array);
The easiest way to do it would be this: 最简单的方法是:
keyword_array.filter(keyword => searchString.includes(keyword));
You can learn more about filter
here . 您可以在此处了解有关
filter
更多信息。 I highly recommend learning about how to use map
, reduce
and filter
. 我强烈建议您学习如何使用
map
, reduce
和filter
。 They are your best friends. 他们是你最好的朋友。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.