开发者

need a regular expression to search a matching last name

I have a javascript array which holds strings of last names. I need to loop开发者_Python百科 this array and separate out the last names which match a given string.

var names = ['woods','smith','smike'];
var test = 'smi';
var c = 0;
var result = new Array();
for(var i = 0; i < names.length; i++)
{
if(names[i].match(test))// need regular expression for this
result[c++] = names[i];
}
return result;

name should match the test string even if the test lies within the name. so... mik should match 'Mike' and 'Smike' also.

Any help is really appreciated!


You can create a regex from a string:

var nameRe = new RegExp("mik", "i");
if(names[i].match(nameRe))
{
    result.push(names[i]);
}

Make sure to escape regex meta-characters though - if your string may contain them. For example ^, $ may result in a miss-match, and *, ? ) and more may result in an invalid regex.

More info: regular-expressions.info/javascript


You can do this without regex:

if (names[i].toLowerCase().indexOf(test.toLowerCase()) >= 0)
    // ...


Javascript string .search is what you're looking for.. You don't even need regex although search supports that too.

var names = ['woods','smith','smike'];
var test = 'smi';
var c = 0;
var result = new Array();
for(var i = 0; i < names.length; i++)
{
if(names[i].toLowerCase().search(test))// need regular expression for this
result.push(names[i]);
}
return result;


You can do this with one regex.

var r = new RegExp(names.join('|'), "igm");

'woods smith'.match(r);


You don't need regex for this, so I'd recommend using string manipulation instead. It's almost (almost!) always better to use string functions instead of regex when you can: They're usually faster, and it's harder to make a mistake.

for(var i = 0; i < names.length; i++)
{
    if(names[i].indexOf(test) > -1)
        //match, do something with names[i]...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜