Elle
Elle

Reputation: 115

How do i check if a string has a number in it

For example:

var variable = `2`
if (variable == {insert checker}) {
  console.log(`string`)
}

I want to know if there is something that would check if my variable is a number or not. I need it so that i can check if the variable is formatted properly. If something like this doesn't exist a function that checks if a number is a number would also be nice to have.

Upvotes: 0

Views: 97

Answers (4)

Vetlix
Vetlix

Reputation: 11

If I'm not mistaken, this regex should do the job. /\d/ is basically the same as /[0-9]/

function hasNumber(string) {
  return /\d/.test(string);
}

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4562

You can use the match method with a regexp, /\d/ means any digit, or the same as: /[0-9]/

var variable = '1'
if (variable.match(/\d/)) {
  console.log('number');
} else{
  console.log('not a number');
}	

Upvotes: 1

tuhin47
tuhin47

Reputation: 6058

isNaN return is not a number. You can verify by this javascript function.

console.log(!isNaN(111));
console.log(!isNaN("111"));
console.log(!isNaN("11asd"));

Upvotes: 2

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

 if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }


function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Upvotes: 3

Related Questions