問題描述
如何區分數字字符串和字符串? (How do i distinguish between number string and character string?)
var snumber1 = "123456789";
var scharacter2 = "abcdefgh";
there're two strings. how do i make sure snumber1 contains only numbers?? What regex??
‑‑‑‑‑
參考解法
方法 1:
The regex to determine if something is just numbers is this:
"^\d+$" or "^[0‑9]+$"
Source: StackOverFlow 273141
方法 2:
var snumber1 = "123456789";
//built‑in function
alert ( !isNaN ( snumber1 ) );
//regexp
alert ( /^[0‑9]+$/.test ( snumber1 ) );
//another regexp
alert ( /^\d+$/.test ( snumber1 ) );
//convert to Number object
alert ( parseFloat ( snumber1 ) === Number ( snumber1 ) );
方法 3:
You need this function:
isNaN(string)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN
方法 4:
Regular expressions are unnecessary:
var snumber1 = "123456789",
scharacter2 = "abcdefgh";
if ( isNaN(+snumber1) ) {
alert('snumber is not a number!');
}
if ( !isNaN(+scharacter2) ) {
alert('scharacter2 is not a string!');
}
Note that I am using the +
operator to do type coercion. Doing so will always result in a number or NaN. If you use the parseInt
or parseFloat
functions you could get '10' from parseInt('010abc', 10)
. This clearly doesn't pass your test for "only numbers" (*).
方法 5:
You should use SWITCH
statements instead of IF
.
var valueA=100
switch(/^[0‑9]+$/.test( valueA ))
{
case false:
alert ("'" + valueA + "'" + " Is NOT a number.Try Again");
break;
case true;
alert ("you've got numbers")
break;
}
This will return true
.
(by DrStrangeLove、JakeJ、Bakudan、Joe、James Sumners、CodeyKane)