(Built-in) way in JavaScript to check if a string

2018-12-31 08:47发布

I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

25条回答
心情的温度
2楼-- · 2018-12-31 09:25

The accepted answer for this question has quite a few flaws (as highlighted by couple of other users). This is one of the easiest & proven way to approach it in javascript:

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

Below are some good test cases:

console.log(isNumeric(12345678912345678912)); // true
console.log(isNumeric('2 '));                 // true
console.log(isNumeric('-32.2 '));             // true
console.log(isNumeric(-32.2));                // true
console.log(isNumeric(undefined));            // false

// the accepted answer fails at these tests:
console.log(isNumeric(''));                   // false
console.log(isNumeric(null));                 // false
console.log(isNumeric([]));                   // false
查看更多
人气声优
3楼-- · 2018-12-31 09:26

Quote:

isNaN(num) // returns true if the variable does NOT contain a valid number

is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.

Better to use:

var num = /^\d+$/.test(num)
查看更多
长期被迫恋爱
4楼-- · 2018-12-31 09:28

My solution:

// returns true for positive ints; 
// no scientific notation, hexadecimals or floating point dots

var isPositiveInt = function(str) { 
   var result = true, chr;
   for (var i = 0, n = str.length; i < n; i++) {
       chr = str.charAt(i);
       if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator
         result = false;
         break;
       };
       if (i == 0 && (chr == "0" || chr == ",")) {  //should not start with 0 or ,
         result = false;
         break;
       };
   };
   return result;
 };

You can add additional conditions inside the loop, to fit you particular needs.

查看更多
冷夜・残月
5楼-- · 2018-12-31 09:29

Maybe there are one or two people coming across this question who need a much stricter check than usual (like I did). In that case, this might be useful:

if(str === String(Number(str))) {
  // it's a "perfectly formatted" number
}

Beware! This will reject strings like .1, 40.000, 080, 00.1. It's very picky - the string must match the "most minimal perfect form" of the number for this test to pass.

It uses the String and Number constructor to cast the string to a number and back again and thus checks if the JavaScript engine's "perfect minimal form" (the one it got converted to with the initial Number constructor) matches the original string.

查看更多
春风洒进眼中
6楼-- · 2018-12-31 09:32

I do it like this:

function isString(value)
{
    return value.length !== undefined;
}
function isNumber(value)
{
    return value.NaN !== undefined;
}

Of course isString() will be tripped up here if you pass some other object that has 'length' defined.

查看更多
像晚风撩人
7楼-- · 2018-12-31 09:32

Old question, but there are several points missing in the given answers.

Scientific notation.

!isNaN('1e+30') is true, however in most of the cases when people ask for numbers, they do not want to match things like 1e+30.

Large floating numbers may behave weird

Observe (using Node.js):

> var s = Array(16 + 1).join('9')
undefined
> s.length
16
> s
'9999999999999999'
> !isNaN(s)
true
> Number(s)
10000000000000000
> String(Number(s)) === s
false
>

On the other hand:

> var s = Array(16 + 1).join('1')
undefined
> String(Number(s)) === s
true
> var s = Array(15 + 1).join('9')
undefined
> String(Number(s)) === s
true
>

So, if one expects String(Number(s)) === s, then better limit your strings to 15 digits at most (after omitting leading zeros).

Infinity

> typeof Infinity
'number'
> !isNaN('Infinity')
true
> isFinite('Infinity')
false
>

Given all that, checking that the given string is a number satisfying all of the following:

  • non scientific notation
  • predictable conversion to Number and back to String
  • finite

is not such an easy task. Here is a simple version:

  function isNonScientificNumberString(o) {
    if (!o || typeof o !== 'string') {
      // Should not be given anything but strings.
      return false;
    }
    return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
  }

However, even this one is far from complete. Leading zeros are not handled here, but they do screw the length test.

查看更多
登录 后发表回答