开发者

javascript regexp help passing in a var to be included as part of the match

开发者 https://www.devze.com 2023-02-10 22:49 出处:网络
Need some help from you javascript regexp pro\'s I have a function that I want to pass in some a \"value\" and a list of accepted characters.This function works in php, but the javascript variables d

Need some help from you javascript regexp pro's

I have a function that I want to pass in some a "value" and a list of accepted characters. This function works in php, but the javascript variables don't work the same as in php, so I need some guiadance.

I would like to call this function like this:

isAlphaNumeric(myValue, "_-"); 

This would allow any number, or letter as well as the underscore and the hyphen, but no other characters

This is the function I have, but doesn't quite work right.

function isAlphaNumeric(value, allow)
{
    var result = /^[A-Za-z0-9+allow+]+$/.test(value)开发者_StackOverflow中文版;
    return result;
}

How can I accomplish what I'm after?

Thanks for the help.


Use RegExp object constructor

function isAlphaNumeric(value, allow)
{
    var re = new RegExp( '^[A-Za-z0-9'+allow+']+$');
    var result = re.test(value);
    return result;
}

or

function isAlphaNumeric(value, allow)
{
    return new RegExp( '^[A-Za-z0-9'+allow+']+$').test(value);
}


By creating a RegExp() object.

function isAlphaNumeric(value, allow) {
    var re = new RegExp('^[a-z0-9' + (allow ? allow : '') + ']+$');

    return re.test(value);
}


Javascript doesn't handle variables inside strings/regexs directly. You have to create the Regex using the constructor like this:

function isAlphaNumeric(value, allow)
{
    var result = new RegExp("^[A-Za-z0-9" + allow + "]+$").test(value);
    return result;
}

Tested on: http://jsfiddle.net/ZLdtw/

Check this other SO question for more info on this concatenation.

0

精彩评论

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