如何使用javascript搜索句子中的多个单词
下面的代码搜索句子中的特定单词(最佳),并根据结果返回true或false 现在我需要升级以允许它搜索多个单词,例如“站点,所有,世界”如何使用javascript搜索句子中的多个单词,javascript,Javascript,下面的代码搜索句子中的特定单词(最佳),并根据结果返回true或false 现在我需要升级以允许它搜索多个单词,例如“站点,所有,世界” 您可以扩展代码并将其更改为函数 var myString='Stackoverflow是世界上所有开发人员的最佳站点'; 功能搜索(输入){ 变量a=新的RegExp('\\b'+input+'\\b'); 返回a.test(myString) } console.log(['site','all','world','blah blah'].some(e=>
您可以扩展代码并将其更改为函数
var myString='Stackoverflow是世界上所有开发人员的最佳站点';
功能搜索(输入){
变量a=新的RegExp('\\b'+input+'\\b');
返回a.test(myString)
}
console.log(['site','all','world','blah blah'].some(e=>search(e))
这里有一个很好的正则表达式资源:
添加了blah
来演示
var myString='Stackoverflow是世界上所有开发人员的最佳站点';
var multiple|u Word='best | BLAH | world';
var a=新的RegExp('\\b'+多个单词+'\\b');
警报(a.test(myString));//false
使用数组#与|
conststr='Stackoverflow是世界上所有开发者的最佳站点';
const words1=[“最佳”、“站点”、“随机”];
const words2=['will','fail','always'];
常量a=newregexp('\\b'+words1.join(“|”)+'\\b');
const b=new RegExp('\\b'+words2.join(“|”)+'\\b');
console.log(a.test(str));
console.log(b.test(str))代码>以下是使用includes()执行此操作的示例
let words=[“the”,“best”,“world”];
让words2=[“the”,“best”,“world”,“apple”];
var myString='Stackoverflow是世界上所有开发人员的最佳站点';
函数校验字(str,words){
为了(让一个字一个字){
//如果单词arr中不存在的单词是str,它将返回false
如果(!str.includes(word))返回false
}
//若在循环中false不返回,则表示所有单词exist都是str,所以返回true
返回true;
}
log(checkWords(myString,words));
log(checkWords(myString,words2))我一点也不清楚你在问什么。预期的输入和输出是什么?best | site | world
是您想要的。尽管@jornsharpe上有一点,但可能是必须包含所有单词?嗨,jornsharpe。如果在句子中发现这三个词中的任何一个,我需要它返回true;如果在句子中没有这三个词,则返回false
var myString = 'Stackoverflow is the best site for all developers in the world';
var multiple_Word = 'best';
var a = new RegExp('\\b' + multiple_Word + '\\b');
alert (a.test(myString)); // false