Skip to main content

Archive

Show more

How to check a string contains numeric digits using javascript

how-to-check-string-contains-numeric-digits-using-javascript


Question: How to check a string contains numeric digits using javascript

Answer: We will discuss three methods which will tell us that the given string must contain at least one number.

First: using simple expression concept.

var myString = "rustcode95@gmail.com"; // String

const myExpression = /\d/;   // Regular expression

console.log(myExpression.test(myString)); // true

output:

true


Second: using 'charAt()' function.

var myString = "rustcode95@gmail.com";

function checkNumbers(input) {
  let str = String(input);
  for (let i = 0; i < str.length; i++) {
    if (!isNaN(str.charAt(i))) {
      console.log(str.charAt(i));
      return true;
    }
  }
}

console.log(checkNumbers(myString));

output:

9
true


Third: using 'split()' function.

var myString = "rustcode95@gmail.com";

function checkNumbers(inputString) {
  let count = 0;
  var splitVar = inputString.split("");
  
  splitVar.forEach(function (e) {
    if (!isNaN(e)) {
      count++;
    } 
  });
  
  if(count > 0) {
    return true;
  } 
  else {
    return false;
  }
}

console.log(checkNumbers(myString));

output:

true



We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments