Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex For only numbers and no white spaces [duplicate]

I was very surprised that I didn't find this already on the internet. is there's a regular expression that validates only digits in a string including those starting with 0 and not white spaces

here's the example I'm using

  function ValidateNumber() {

  var regExp = new RegExp("/^\d+$/");
  var strNumber = "010099914934";
  var isValid = regExp.test(strNumber);
  return isValid;
}

but still the isValid value is set to false

like image 630
Scarnet Avatar asked Apr 03 '16 08:04

Scarnet


1 Answers

You could use /^\d+$/.

That means:

  • ^ string start
  • \d+ a digit, once or more times
  • $ string end

This way you force the match to only numbers from start to end of that string.

Example here: https://regex101.com/r/jP4sN1/1
jsFiddle here: https://jsfiddle.net/gvqzknwk/


Note:

If you are using the RegExp constructor you need to double escape the \ in the \d selector, so your string passed to the RegExp constructor must be "^\\d+$".


So your function could be:

function ValidateNumber(strNumber) {
    var regExp = new RegExp("^\\d+$");
    var isValid = regExp.test(strNumber); // or just: /^\d+$/.test(strNumber);
    return isValid;
}
like image 151
Sergio Avatar answered Oct 20 '22 01:10

Sergio