Reg Exp: Match Numbers And Spaces Only
I am writing a js script to validate a form field and I need to check it contains only numbers and possibly whitespace. What is the regular expression for that?
Solution 1:
You can try something like
var isSpacedNumber = (/^\s*\d+\s*$/i).test(<string value>);
The regular expression consists of the parts
- "^" saying that match should start from beginning of input
- \s* meaning zero or more (*) whitespaces (\s)
- \d+ meaning one or more (+) digits (\d)
- \s* meaning zero or more (*) whitespaces (\s)
- $ meaning match end of string
Without ^ and $ the regular expression would capture any number in a string, and thus "number is 123" would give positive indication.
More information about javascript regular expression can be found here
Solution 2:
var str = "Watch out for the rock!".match(/^[\d\s]+$/g)
Solution 3:
Try this regular expression:
/^[\d\s]+$/
Solution 4:
The \d
character matches any digit which is the same as using [0-9]
, the \s
character matches any whitespace.
To check if a string is a number (assuming there are no dots or comma's):
var regex = /^[\d]+$/;
However, an easier method for you would be to use the isNaN()
function. If the function returns true, the number is illegal (NaN
). If it returns false, it's a correct number.
if( !isNaN( value ) ) {
// The value is a correct number
} else {
// The value is not a correct number
}
Post a Comment for "Reg Exp: Match Numbers And Spaces Only"