Same question has been asked here: How to pass a regular expression as a function parameter, but I still can't get it work.
This is the string expression of regular expression that I used to test email:
var regexp="^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
and if I put it to firebug execute like this:
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"/.test("[email protected]")
it will give what I want,but If taking it as parameter to passing it to function:
function bool validate(var value, var regexp){
//escape special characters
regexp=String(regexp).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
return new RegExp(regexp,'g').test(value)
}
like this:
validate("[email protected]",regexp);
It will give me false.Please tell what mistakes I have made,thanks.
Update: sorry,as @Bhojendra - C-Link Nepal said,there is a typing mistake when translating gwt's jsni code to this,right code should be:
function validate(value, regexp){
//escape special characters
var regexp = regexp.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
return new RegExp(regexp,'g').test(value);
}
but it doesn't work still.
validate(...)is returning false. The code will not execute at all because of the syntax error infunction bool validate(var..., so it will generate a console error. You need to read up on basic JS syntax for defining functions. Please do not post questions with code which generates console errors, unless it is the console error itself which is stumping you.