Sometimes, we want to check for strings with only numbers and dot with JavaScript.
In this article, we’ll look at how to check for strings with only numbers and dot with JavaScript.
How to check for strings with only numbers and dot with JavaScript?
To check for strings with only numbers and dot with JavaScript, we can call the JavaScript string match
method to return matches of the pattern.
For instance, we write:
const validate = (s) => {
const rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
console.log(validate('123.45'))
console.log(validate('foo'))
We define the validate
function that has the rgx
regex that matches strings with digits and dots.
And we call match
with rgx
to return the matches of the digit and dot pattern found in string s
.
Therefore, we get ['123.45', index: 0, input: '123.45', groups: undefined]
and null
logged respectively.
Conclusion
To check for strings with only numbers and dot with JavaScript, we can call the JavaScript string match
method to return matches of the pattern.