Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for words in string

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.

like image 981
Samhakadas Avatar asked Jun 17 '17 12:06

Samhakadas


People also ask

How do you search for an element in a string?

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.

How do I search for a word in a string?

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.

How do I find a word in a string C++?

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.

How do I find a word in a string Python?

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.


1 Answers

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!";
}
like image 171
Mateusz Kocz Avatar answered Nov 03 '22 14:11

Mateusz Kocz