Javascript Regular Expression is working fine first time but not second time, working again for 3rd time and not for 4th and so on 🙁
Script :
<script language="javascript" type="text/javascript">
var reg = /[^\w]/gi;
function checkNonWordChars() {
var str = $("#TestTextbox").val();
if (reg.test(str)) {
alert('!!! Non-Word Char Exists !!!');
}
else {
alert('input accepted');
}
}
</script>
HTML :
<input type="text" id="TestTextbox" />
<input type="button" value="Test" onclick="checkNonWordChars();" />
If I click on button once, it will fire an alert saying that “!!! Non-Word Char Exists !!!” but if I click it again, it will fire an alert saying “input accepted” 🙁
OPTION 1
Use the constructor rather than the literal notation:
More about differences between the two here: https://developer.mozilla.org/en-US/docs/Core_JavaScript_1.5_Guide/Regular_Expressions?redirect=no
OPTION 2
Mark the end of the string with a
$sign:OPTION 3
If your regular expression uses the “g” flag, you can use the
execmethod multiple times to find successive matches in the same string. When you do so, the search starts at thesubstringofstrspecified by the regular expression’slastIndexproperty(
testwill also advance the lastIndex property).Source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec
Therefore, in your case the test will work only 1st, 3rd, 5th, … time.
Only in Firefox 3 there is a flag
y, when specifiedexecalways starts from 0 notlastIndexbut this is probably not useful in your case.You can remove the
gflag.