我的最终目标是验证输入字段。输入可以是字母也可以是数字。
当前回答
这段代码还有助于“检测给定字符串中的数字”,当发现数字时,它会停止执行。
function hasDigitFind(_str_) {
this._code_ = 10; /*When empty string found*/
var _strArray = [];
if (_str_ !== '' || _str_ !== undefined || _str_ !== null) {
_strArray = _str_.split('');
for(var i = 0; i < _strArray.length; i++) {
if(!isNaN(parseInt(_strArray[i]))) {
this._code_ = -1;
break;
} else {
this._code_ = 1;
}
}
}
return this._code_;
}
其他回答
你可以使用javascript来做到这一点。不需要Jquery或Regex
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');
}
function validate(){
var re = /^[A-Za-z]+$/;
if(re.test(document.getElementById("textboxID").value))
alert('Valid Name.');
else
alert('Invalid Name.');
}
当字符串以整数的表示形式开始时,parseInt提供整数:
(parseInt '1a') is 1
..所以也许:
isInteger = (s)->
s is (parseInt s).toString() and s isnt 'NaN'
(isInteger 'a') is false
(isInteger '1a') is false
(isInteger 'NaN') is false
(isInteger '-42') is true
原谅我的CoffeeScript。
你也可以试试lodash:
const isNumeric = number =>
_.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))
下面的代码检查相同的数字,序列号和反向的数字序列。
function checkNumSequnce(arrayNM2) {
inseqCounter=1;
continousSeq = 1;
decsequenceConter = 1;
var isequence = true;
for (i=0;i<arrayNM2.length-1;i++) {
j=i+1;
if (arrayNM2[i] == arrayNM2[i+1]) {
if(inseqCounter > 1 || decsequenceConter > 1){
isequence = false; break;
}
continousSeq++;
}
else if (arrayNM2[j]- arrayNM2[i] == 1) {
if(decsequenceConter > 1 || continousSeq > 1){
isequence = false; break;
}
inseqCounter++;
} else if(arrayNM2[i]- arrayNM2[j] == 1){
if(inseqCounter > 1 || continousSeq > 1){
isequence = false; break;
}
decsequenceConter++;
}else{
isequence= false;
break;
}
};
console.log("isequence: "+ isequence);
};
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?