Skip to content

JavaScript string is number check | Example code

  • by

Use isNaN() method to check string is number in JavaScript. This works regardless of whether the variable content is a string or number.

isNaN(num)

The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). It returns true if the variable does NOT contain a valid number.

Check if a string contains only digits.

let isnum = /^\d+$/.test(val);

Check JavaScript string is a number

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

    console.log("Valid num",isNaN('195'))
    console.log("Valid num",isNaN('boo'))
    console.log("Valid num",isNaN('100px'))

  </script>
</body>
</html>

Output:

JavaScript string is number check

Creating a function that negates the output of the isNaN() function.

function isNum(val){
  return !isNaN(val)
}
console.log(isNum('ABC'));          
console.log(isNum('12345'));        
console.log(isNum('-1'));

Output:

false
true
true

Do comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *