[javascript] Check whether an input string contains a number in javascript

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

This question is related to javascript string numbers validation

The answer is


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

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

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 class is 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 \d could mean any digit.

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 only of 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 Matching with Regular Expressions.


You can do this using javascript. No need for Jquery or 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');
}

You can also try lodash:

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

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

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


We can check it by using !/[^a-zA-Z]/.test(e)
Just run snippet and check.

_x000D_
_x000D_
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';
  }
}
_x000D_
input {
  padding: 5px;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
_x000D_
_x000D_
_x000D_


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

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

function isNumeric(n) 
{
  return !isNaN(n);
}

parseInt provides integers when the string begins with the representation of an integer:

(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.


This is what you need.

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 

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.

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

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

Below code checks for same number, sequence number and reverse number sequence.

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

  };

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.");
 }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery