搜索字符串中的单词 [英] Searching for words in string

查看:58
本文介绍了搜索字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数从数组中查找包含所有单词的字符串.

I'm trying to make a function that finds the string that contains all words from an array.

我已经尝试过了:

function multiSearchOr(text, searchWords){
    var searchExp = new RegExp(searchWords.join("|"),"gi");
    return (searchExp.test(text))?"Found!":"Not found!";
}

alert(multiSearchOr("Hello my name sam", ["Hello", "is"]))

但这只会在找到其中一个单词时提醒找到".

But this only alert "Found" when one of the words have been found.

当所有单词都在字符串中时,我需要它来提醒我.

I need it to alert me when all the words are in the string.

一个例子:

var sentence = "I love cake"    
var words = ["I", "cake"];

我希望应用程序在从字符串句子中的数组中找到所有单词时提醒我.当它只找到其中​​一个词时就没有.

I want the application to alert me when it finds all of the words from the array in the string sentence. Not when it only found one of the words.

推荐答案

如果您只想使用单个正则表达式,则在构造表达式时需要使用正向前行.看起来像这样:

If you're interested in using only a single regular expression, then you need to use a positive lookahead when constructing your expression. It will look something like that:

'(?=\\b' + word + '\\b)'

鉴于此构造,您可以创建正则表达式并测试匹配项:

Given this construction, you can then create your regular expression and test for the match:

function multiSearchOr(text, searchWords){
    var regex = searchWords
        .map(word => "(?=.*\\b" + word + "\\b)")
        .join('');
    var searchExp = new RegExp(regex, "gi");
    return (searchExp.test(text))? "Found!" : "Not found!";
}

这篇关于搜索字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆