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.
You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.
To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.
string find in C++String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0.
We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved.
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!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With