只包含整数数字
用正则表达式即可实现。
var num = function(str) {
var patrn = /^[0-9]{1,20}$/;
var bool = true;
if (!patrn.exec(str)) {
bool = false;
}
console.log(bool);
return bool;
}
num("3.4");
num("34");
num("");
num(" ");
num("0-34");
num(">");
得到的结果:
false
true
false
false
false
false
包含带小数点的数字
若使用上面的正则匹配,会将小数点识别为非数字字符。可利用 Number() 将字符串强制转换成数字,若结果不为 NaN,则说明该字符串只包含数字。
但是 Number() 会将空字符串与空格都转换为 0,所以要先将空字符串与空格排除。
var strToNum = function(str) {
var convertNum = Number(str); // 将字符串强制转换为数字
if (str === "") { // 排除空字符串
console.log("\"" + str + "\" is an Empty String.");
} else {
if (str.includes(" ")) { // 排除空格
console.log("\"" + str + "\" contains spaces.");
} else {
if (isNaN(convertNum)) {
console.log("\"" + str + "\" can't be converted into a number.");
} else {
console.log("\"" + str + "\" can be converted into " + convertNum + ".");
}
}
}
}
// 测试函数
strToNum("34");
strToNum("0.34");
strToNum(",");
strToNum(" ");
strToNum("");
strToNum(" 89 ");
strToNum("2.34");
strToNum("2-34");
得到的结果:
"34" can be converted into 34.
"0.34" can be converted into 0.34.
"," can't be converted into a number.
" " contains spaces.
"" is an Empty String.
" 89 " contains spaces.
"2.34" can be converted into 2.34.
"2-34" can't be converted into a number.