开发者

Extracting number from a string

What is th开发者_运维问答e best way to get the number from a string.

The string will always start with n and end with any number i.e.:

n1
n2
n3
n10
n100
n1000
n99999
n9999999999999

and so on.


If you can guarantee the string will always look like that, then

num = parseInt(str.substring(1));


If it always starts with a single 'n', just keep it simple:

var number = parseInt(value.replace('n', ''));


Number.of = function (number) {
    if (typeof number === "number")
        return number;

    var number = number + '',
        regnum = /(-)?[0-9]+\.?[0-9]*/.exec(number);

    return regnum ? (new Function('return ' + regnum[0]))() : 0;
};

Then just run..

Number.of('n12345'); // 12345

Mine is an incredibly careful approach to it, but what will pull a number out of anything.

Number.of('Hel5lo'); // 5

And always returns a number.

Number.of('There is no number here.'); // 0

That may or may not be helpful to you though.


You can use String.prototype.substr[docs] (or substring) and an unary + to convert the string to a number:

var number = +str.substr(1);


I's suggest:

$('dt').each(
    function(){
        var n = $(this).text().substring(1);
        $('<dd />').text(n).insertAfter($(this));
    });

JS Fiddle demo.

It doesn't matter, obviously, which elements you choose to use (I opted for dt and dd for the implied relationship between the input and the output). The important part is the substring() function; the value of 1 refers to the starting point of the resulting substring (from the second character, as JavaScript works with zero-based arrays).

Had a second number been passed, in the form substring(1,4) the resulting substring would have started from the second character and ended with the fifth, unless the string on which substring() is working is of a length shorter than the second argument, in which case it's treated as being equal to the length of the string.

Reference:

  • substring() at the Mozilla Developer Center.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜