EN
JavaScript - check if string contains only numbers
14
points
In this article, we want to show how in JavaScript using simple regular expressions, check if the string contains only numbers.
Example expressions:
/^[0-9]+$/
/^[0-9]{1,}$/
/^\d+$/
/^\d{1,}$/
For example, we can select the first one, and do some tests with match()
function:
// ONLINE-RUNNER:browser;
var expression = /^[0-9]+$/;
var text = '1000500100900';
if (text.match(expression)) {
console.log('I am number!');
}
Alternative solution
// ONLINE-RUNNER:browser;
var expression = /^[0-9]+$/;
var text = '1000500100900';
if (expression.test(text)) {
console.log('I am number!');
}