Use the isNaN() method to check the string 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 if the 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:
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
Using Regular Expression
You can also use regular expressions to check if a string contains only numeric characters.
function isStringNumber(str) {
return /^\d+$/.test(str);
}
console.log(isStringNumber("123")); // true
console.log(isStringNumber("abc")); // false
Using Unary Plus Operator
Another method is to use the unary plus operator (+
) to attempt to convert the string into a number. If the conversion is successful, it’s a number; otherwise, it’s not.
function isStringNumber(str) {
return !isNaN(+str);
}
console.log(isStringNumber("123")); // true
console.log(isStringNumber("abc")); // false
Choose the method that best fits your requirements and coding style.
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