My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the
typeofoperator instead. But JavaScript doesn’t have dedicated types forintandfloat. So you have to do the integer check yourself. Iffloordoesn’t change the value, then you have an integer.There is one more caveat.
Infinityis anumberand callingMath.floor()on it will result inInfinityagain, so you get a false positive there. You can change that like this:Seeing your regex you might want to accept only positive integers: