Reputation: 765
Consider that I have a list of user names and I need to search for a user with a search key. For every username, if it matches the key I will add it to the search results, as indicated by the following javascript code:
var username_1 = "amal";
var username_2 = "sayed ali mohamed";
var search_key = "am";
var index = username_1.search(search_key);
if(index != -1){
console.log('Username 1 matched')
}
index = username_2.search(search_key);
if(index != -1){
console.log('Username 2 matched')
}
As obvious, only username1
matches the query, but it's noted that both names have the letters 'a' and 'm'. So, if I wanted both names to match, I need to use the following regular expression: .*a.*m.*
Problem: given a string of characters 'c1c2c3...cn', how to convert it to the following string of characters '.*c1.*c2.*c3 ... .*cn.*' in an efficient way with javascript ?
Upvotes: 1
Views: 452
Reputation:
First: the regular expression you want is of the form /a.*b.*c/
, not /a*b*c*/
. The latter expression would only match strings like aaaabbccccc
, and would not match axxxbxxxc
.
Second: the easiest way to convert from "abc"
to /a.*b.*c/
is to split the string on an empty delimiter, then join the resulting array with the wildcard:
var input = "abc";
var regex = new RegExp(input.split("").join(".*"));
Upvotes: 1