Javascript 检查输入字符串是否包含javascript中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5778020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:47:45  来源:igfitidea点击:

Check whether an input string contains a number in javascript

javascriptstringnumbersvalidation

提问by Udara S.S Liyanage

My end goal is to validate an input field. The input may be either alphabetic or numeric.

我的最终目标是验证输入字段。输入可以是字母或数字。

回答by Zon

If I'm not mistaken, the question requires "contains number", not "is number". So:

如果我没记错的话,这个问题需要“包含数字”,而不是“是数字”。所以:

function hasNumber(myString) {
  return /\d/.test(myString);
}

回答by Starx

You can do this using javascript. No need for Jquery or Regex

您可以使用 javascript 执行此操作。不需要 Jquery 或 Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

在实施的同时

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

更新:要检查字符串中是否包含数字,您可以使用正则表达式来执行此操作

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}

回答by Jishnu A P

function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}

回答by Elon Zito

It's not bulletproof by any means, but it worked for my purposes and maybe it will help someone.

它无论如何都不是防弹的,但它对我的目的有用,也许它会帮助某人。

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }

回答by Yash

Using Regular Expressions with JavaScript. A regular expression is a special text string for describing a search pattern, which is written in the form of /pattern/modifiers where "pattern" is the regular expression itself, and "modifiers" are a series of characters indicating various options.
         The character classis the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z]could stand for the upper case alphabet, and \dcould mean any digit.

在 JavaScript 中使用正则表达式。正则表达式是用于描述搜索模式的特殊文本字符串,它以 /pattern/modifiers 的形式编写,其中“pattern”是正则表达式本身,“modifiers”是表示各种选项的一系列字符。
         字符类是文字赛后最基本的正则表达式的概念。它使一个小的字符序列匹配一组更大的字符。例如,[A-Z]可以代表大写字母,\d可以代表任何数字。

From below example

从下面的例子

  • contains_alphaNumeric? It checks for string contains either letter or number (or) both letter and number. The hyphen (-) is ignored.
  • onlyMixOfAlphaNumeric? It checks for string contain both letters and numbers onlyof any sequence order.

Example:

例子:

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) );

Out put:

输出:

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 Pattern Matchingwith Regular Expressions.

java正则表达式模式匹配

回答by Herbert Su

One way to check it is to loop through the string and return true (or false depending on what you want) when you hit a number.

检查它的一种方法是遍历字符串并在您点击一个数字时返回 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;
        }
    }
}

回答by NVRM

To test if any char is a number, without overkill?, to be adapted as need.

测试任何字符是否是数字,而不是矫枉过正?,根据需要进行调整。

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)

回答by Darex1991

You can also try lodash:

你也可以试试 lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

回答by Neil Stockbridge

parseIntprovides integers when the string begins with the representation of an integer:

parseInt当字符串以整数表示形式开始时提供整数:

(parseInt '1a')  is  1

..so perhaps:

..所以也许:

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

Pardon my CoffeeScript.

请原谅我的 CoffeeScript。

回答by Khan Usama

This code also helps in, "To Detect Numbers in Given String"when numbers found it stops its execution.

当发现数字停止执行时,此代码还有助于“检测给定字符串中的数字

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_;
}