我的最终目标是验证输入字段。输入可以是字母或数字。
如果我没记错的话,问题需要“包含数字”,而不是“是数字”。所以:
function hasNumber(myString) {
return /\d/.test(myString);
}
您可以使用 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');
}
这就是您所需要的。
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.");
}
使用JavaScript 中的正则表达式。正则表达式是用于描述搜索模式的特殊文本字符串,以 /pattern/modifiers 的形式编写,其中“pattern”是正则表达式本身,“modifiers”是一系列指示各种选项的字符。
字符类是字面匹配之后最基本的正则表达式概念。它使一小段字符序列与一大组字符相匹配。例如,
[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}
java 模式匹配与正则表达式。
function isNumeric(n)
{
return !isNaN(n);
}
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)
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;
}
}
}
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。
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))
“检测给定字符串中的数字”当发现数字时,它会停止执行。
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_;
}
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);
};
我们可以使用 !/[^a-zA-Z]/.test(e)
function handleValueChange() {
if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
var x = document.getElementById('result');
x.innerHTML = 'String does not contain number';
} else {
var x = document.getElementById('result');
x.innerHTML = 'String does contains number';
}
}
input {
padding: 5px;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
我的最终目标是验证输入字段。输入所以这是一个返回可以是字母或数字。
-- 哦
boolean
答案的函数,
true
如果传递的
input
具有
Number
值或严格的alphabetic 字符串值,
false
否则:
const isAlphaOrNumeric = input => {
if ('' === input.value.trim())
return false // empty
if (!Number.isNaN(Number(input.value)))
return true //'number'
return /^[a-zA-Z]+$/.test(input.value.trim()) // 'alphabetic'
}
const isAlphaOrNumeric = input => {
if ('' === input.value.trim())
return false
if (!Number.isNaN(Number(input.value)))
return true
return /^[a-zA-Z]+$/.test(input.value.trim())
}
const f = document.querySelector('form')
const test = f.querySelector('[name="test"]')
const test2 = f.querySelector('[name="test2"]')
const test3 = f.querySelector('[name="test3"]')
f.onsubmit = e => {
e.preventDefault()
console.log(test.value, isAlphaOrNumeric(test))
console.log(test2.value, isAlphaOrNumeric(test2))
console.log(test3.value, isAlphaOrNumeric(test3))
}
<form>
<input name="test" value="abc"><br>
<input name="test2" value="-3.14"><br>
<input name="test3" value="AFF4B3"><br>
<button>
check it
</button>
</form>
'test123'.split('').reduce((result,ch) => ch.charCodeAt(0) >= 48 && ch.charCodeAt(0) <= 57), false);
function check_string(str){
const number_pattern = /\d/;
return number_pattern.test(str)
}
let sample_string = "Hello World 1234";
let is_string_contains_number = check_string(sample_string);
//output : true [if the string contains number in it]
const isNumeric = number =>
_.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))