0
var snumber1 = "123456789";
var scharacter2 = "abcdefgh";

there're two strings. how do i make sure snumber1 contains only numbers?? What regex??

DrStrangeLove
  • 10,539
  • 16
  • 57
  • 70
  • A regex isn't really necessary here, but if you're curious it would be `/^\d+$/` for only numbers, or `/^\d*$/` if you want to match the empty string also. – Ismail Badawi Jul 18 '11 at 14:39

6 Answers6

2

The regex to determine if something is just numbers is this:

"^\d+$"  or  "^[0-9]+$"

Source: StackOverFlow 273141

Community
  • 1
  • 1
JakeJ
  • 1,362
  • 3
  • 14
  • 34
2
var snumber1 = "123456789";
//built-in function
alert ( !isNaN ( snumber1 ) );
//regexp
alert ( /^[0-9]+$/.test ( snumber1 ) );
//another regexp
alert ( /^\d+$/.test ( snumber1 ) );
//convert to Number object
alert ( parseFloat ( snumber1 ) === Number ( snumber1 ) );
Bakudan
  • 18,466
  • 9
  • 50
  • 71
1

You need this function:

isNaN(string)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN

Joe
  • 77,580
  • 18
  • 124
  • 143
1

Regular expressions are unnecessary:

var snumber1 = "123456789",
    scharacter2 = "abcdefgh";

if ( isNaN(+snumber1) ) {
  alert('snumber is not a number!');
}

if ( !isNaN(+scharacter2) ) {
  alert('scharacter2 is not a string!');
}

Note that I am using the + operator to do type coercion. Doing so will always result in a number or NaN. If you use the parseInt or parseFloat functions you could get '10' from parseInt('010abc', 10). This clearly doesn't pass your test for "only numbers" (*).

James Sumners
  • 14,055
  • 10
  • 57
  • 75
  • Better yet, considering isNaN has edge cases, use `if(+sNumber1 != +sNumber1)`, which is true iff sNumber1 is not a number. – Thaddee Tyl Jul 18 '11 at 16:04
  • @Thaddee: `+sNumber != +sNumber` has *exactly* the same edge cases as `isNaN` with an additional downside that it's quite a bit slower than `isNaN` - believe it or not, `isNaN` performs the same number conversion on the argument passed before checking it. This also means that the `+` in `isNaN(+str)` is completely unnecessary and just adds extra overhead with no benefit. – Andy E Sep 16 '11 at 08:12
  • 1
    @Andy E, I wasn't aware of that. Thank you. – James Sumners Sep 16 '11 at 12:39
1

You should use SWITCH statements instead of IF.

var valueA=100

switch(/^[0-9]+$/.test( valueA ))
{
    case false:
        alert ("'" + valueA + "'" + " Is NOT a number.Try Again");
        break;
    case true;
        alert ("you've got numbers")
        break;
}

This will return true.

Myrtle
  • 5,651
  • 32
  • 47
CodeyKane
  • 11
  • 1
0

you could use parseInt

if (parseInt(snumber1) == snumber1){ alert('is a number'); }
Mihai Iorga
  • 38,217
  • 14
  • 107
  • 106