Skip to content Skip to sidebar Skip to footer

Check Legal Characters By Regular Expression But With Unexpected Result

I have defined some characters which are legal to use. var reg= /[-!*() ~{}'<>._a-zA-Z0-9]/g In order to t

Solution 1:

It's because when a global regex is used multiple times, the lastIndex property gets updated.

MDN:

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

So, you need to remove the global flag. It doesn't affect the result in anyway, as it still returns false when the first non-allowed character is encountered.


Solution 2:

Remove the g (global) flag.

> var reg= /[-!*() ~{}'<>._a-zA-Z0-9]/;
undefined
> var arr= ["-", ".", "!", "~", "*", "(", ")", "'", "_","<",">"];
undefined
> for(var i=0 ;i < arr.length;i++)
... {
... console.log( arr[i] +"  " + reg.test(arr[i]));
... }
-  true
.  true
!  true
~  true
*  true
(  true
)  true
'  true
_  true
<  true
>  true

Post a Comment for "Check Legal Characters By Regular Expression But With Unexpected Result"