Incorrect JavaScript match in RegEx

I have a little javascript funtcion:

function GetFilteredListLimited(event) {
    var $source = $(event.target);
    var $Pattern = event.data.Pattern;
    var RE = new RegExp($Pattern, 'i');
    if (RE.test($source.val())) {
        console.log('RegEx match');
    }
};

      

Used template:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

      

Which should match most email addresses.

Using http://regexpal.com/ I can see that the template is correct. But for some strange reason the script already matches the 4th character after @

abc @abcd shouldn't match, but it does. Any suggestions?

+3


source to share


1 answer


You need to know the constructor RegExp

where escaped characters must be double-escaped. So, your regex string passed to the RegExp constructor should look like this:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$

      

The fix can be entered as follows:



var RE = new RegExp($Pattern.replace(/\\/g, '\\\\'), 'i');

      

It will work if escaped characters are used sequentially.

+1


source







All Articles