我的最终目标是验证一个输入字段,这个输入可能是字母或数字。
如果我没有误解问题的要求,“包含数字”而不是“是数字”。因此:
function hasNumber(myString) {
return /\d/.test(myString);
}
.test
方法的更多信息,请参见此处:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test - joeljpa您可以使用JavaScript来完成此操作,无需使用Jquery或正则表达式。
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
在实现过程中
var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); }
else { alert('not number'); }
更新:要检查字符串中是否有数字,可以使用正则表达式来实现
var matches = val.match(/\d+/g);
if (matches != null) {
alert('number');
}
matches != null
的意思是不是 undefined
或者 null
,而 matches !== null
则特指不为 null
但可以为 undefined
。 - Natematch()
返回一个数组或 null
。因此,if (matches !== null)
应该是可以的(并且它会让 JSHint 高兴).来源: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match - JasonisFinite()
函数会在传入的值是有限数时返回true,而数字5,000
是一个格式化的数字字符串,不是有限数。 - StarxparseFloat('5,000')
,结果将会是 5
,这就截取走大部分实际数据。它的作用不是从字符串中提取数值/浮点型数值,而是如在 parseFloat('50.65 %')
中可以成功分离并给出 50.65
作为结果。因此,它只是用于检查 parseFloat
是否返回 NaN
。使用双重否定检查 NaN
和 isFinite
可以确保传递的值是数值型,这也是解决方案的原因。 - StarxparseFloat()
而不是解决方案本身。它不会区分它们,因此对于两者都会返回false。感谢您提供的链接,我会阅读一下。 - Starx这就是你需要的。
var hasNumber = /\d/;
hasNumber.test("ABC33SDF"); //true
hasNumber.test("ABCSDF"); //false
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("textboxID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
它并不是绝对可靠的,但对于我的目的而言起到了作用,也许能帮助其他人。
var value = $('input').val();
if(parseInt(value)) {
console.log(value+" is a number.");
}
else {
console.log(value+" is NaN.");
}
Boolean(parseInt("3")) -> true;
Boolean(parseInt("three")) -> false```
- Elon ZitoparseInt("0")
时要小心,它也会返回false。 - Aderemi Dayo[A-Z]
可能代表大写字母,而\d
可能表示任何数字。
从下面的例子中:
contains_alphaNumeric
« 它检查字符串是否包含字母或数字(或者)字母和数字。 连字符(-)被忽略。onlyMixOfAlphaNumeric
« 它检查字符串是否仅包含字母和数字,顺序不限。例子:
function matchExpression( str ) {
var rgularExp = {
contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
containsNumber : /\d+/,
containsAlphabet : /[a-zA-Z]/,
onlyLetters : /^[A-Za-z]+$/,
onlyNumbers : /^[0-9]+$/,
onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
}
var expMatch = {};
expMatch.containsNumber = rgularExp.containsNumber.test(str);
expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);
expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);
return expMatch;
}
// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );
console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );
console.log( "Only Special symbols :\n ", matchExpression(id12) );
输出:
Only Letters:
{containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
{containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
{containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
{containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
{containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
{containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
{containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
{containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
{containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
function isNumeric(n)
{
return !isNaN(n);
}
function isNumeric(n) { return !isNaN(n); }
实现。 - Luca Steeb为了测试一个字符是否是数字,避免过度复杂,可以根据需要进行调整。
const s = "EMA618"
function hasInt(me){
let i = 1,a = me.split(""),b = "",c = "";
a.forEach(function(e){
if (!isNaN(e)){
console.log(`CONTAIN NUMBER «${e}» AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i}`)
c += e
i++
} else {b += e}
})
console.log(`STRING IS «${b}», NUMBER IS «${c}»`)
if (i === 0){
return false
// return b
} else {
return true
// return +c
}
}
hasInt(s)
一种检查方法是循环遍历字符串,当遇到数字时返回true(或false,取决于您的需求)。
function checkStringForNumbers(input){
let str = String(input);
for( let i = 0; i < str.length; i++){
console.log(str.charAt(i));
if(!isNaN(str.charAt(i))){ //if the string is a number, do the following
return true;
}
}
}
我认为提取数字和字符串的方法非常简单易用。
str = "jdghj4874y6jfngvjbng"
let num = []
let strEx = []
for (i = 0; i < str.length; i++) {
if (str[i] >= 0) {
num.push(str[i])
} else {
strEx.push(str[i])
}
}
console.log('nums:', JSON.stringify(num))
console.log('chars:', JSON.stringify(strEx))