Reputation: 984
I wanted to check the availability of multiple strings in a given string ( without using a loop ).
like
my_string = "How to find occurence of multiple sting in a given string using javascript RegExp";
// search operated on this string
// having a-z (lower case) , '_' , 0-9 , and space
// following are the strings wanted to search .( having a-z , 0-9 , and '_')
search_str[0]="How";
search_str[1]="javascript";
search_str[2]="sting";
search_str[3]="multiple";
is there is any regular expression available for this ?
UPDATE : WHAT AM I MISSING
in the answers i found this one is working in the above problem
if (/^(?=.*\bHow\b)(?=.*\bjavascript\b)(?=.*\bsting\b)(?=.*\bmultiple\b)/.test(subject)) {
// Successful match
}
But in this case it is not working.
m_str="_3_5_1_13_10_11_";
search_str[0]='3';
search_str[1]='1';
tst=new RegExp("^(?=.*\\b_"+search_str[0]+"_\\b)(?=.*\\b_"+search_str[1]+"_\\b)");
if(tst.test(m_str)) alert('fooooo'); else alert('wrong');
Upvotes: 1
Views: 340
Reputation: 336108
if (/^(?=.*\bHow\b)(?=.*\bjavascript\b)(?=.*\bsting\b)(?=.*\bmultiple\b)/.test(subject)) {
// Successful match
}
This assumes that your string doesn't contain newlines. If it does, you need to change all the .
s to [\s\S]
.
I have used word boundary anchors to make sure that Howard
or resting
don't accidentally provide a match. If you do want to allow that, remove the \b
s.
Explanation:
(?=...)
is a lookahead assertion: It looks ahead in the string to check whether the enclosed regex could match at the current position without actually consuming characters for the match. Therefore, a succession of lookaheads works like a sequence of regexes (anchored to the start of the string by ^
) that are combined with a logical &&
operator.
Upvotes: 4