[Javascript] How can i check javascript/typescript string contains a number?



1. Goal

hasNumber.test("CCCC33CCC");  //true
hasNumber.test("CCCCCCC");  //false 

How can i check javascript/typescript string contains a number? I want to check string contains a number like this case. I want to validate an input field. The input may be either alphabetic or numeric.

2. Solution

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

hasNumber.test("CCCC33CCC");  //true
hasNumber.test("CCCCCCC");  //false 

You can solve this problem like this way. You can easily solve this problem. It is so easy to find that string has a number.

let hasNumber = /\d/;   
hasNumber.test("CCCC33CCC");  //true
hasNumber.test("CCCCCCC");  //false 

reference

  • https://stackoverflow.com/questions/5778020/check-whether-an-input-string-contains-a-number-in-javascript