下面的代码在句子中搜索特定单词 (best) 并根据结果返回 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
最佳答案
您可以扩展代码并将其更改为函数。
var myString = 'Stackoverflow is the best site for all developers in the world';
function search(input){
var a = new RegExp('\\b' + input + '\\b');
return a.test(myString)
}
console.log(['site', 'all', 'world', 'blah blah'].some(e=>search(e)))
您可以在评论中使用 join 来匹配其中一个。
var myString = 'Stackoverflow is the best site for all developers in the world';
const words1 = ['best', 'site', 'random'];
let reg = `\b${words1.join('|')}\b`
let regex = new RegExp(reg)
console.log(regex.test(myString))
关于javascript - 如何使用javascript在一个句子中搜索多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54484423/