Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  170] [ 7]  / answers: 1 / hits: 15493  / 7 Years ago, sat, june 17, 2017, 12:00:00

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



I have tried this:



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.



An example:



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.


More From » regex

 Answers
32

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!;
}

[#57415] Thursday, June 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arielle

Total Points: 373
Total Questions: 105
Total Answers: 96

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;