How can I check if a number has a - as its start value using javascript?
I tested the following code and it returned me false when I expected it to be true..How can I fix this and why it's returning 开发者_如何转开发me false?
<script type="text/javascript">
var str3 ="-12346dsfs56";
var reg4 =/^(-{1})\d+$/;
alert(reg4.test(str3));
</script>
There are 2 simple ways i can think of.
first if its a number you can check if it's less than 0
if (number < 0) {
// do stuff
}
or in your case a string you can check if the first character is a -
if (str[0] == "-") {
// do stuff
}
The regex returns False because that string is not a number (it contains letters)!
If you drop the $
, the regex will only check if the string begins with a -
and at least one digit. And you can drop the {1}
, it's unnecessary since one occurrence is the default for a regex token.
精彩评论