oshirowanen
oshirowanen

Reputation: 15925

Extracting number from a string

What is the 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.

Upvotes: 0

Views: 131

Answers (5)

McKayla
McKayla

Reputation: 6949

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.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

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:

Upvotes: 0

cHao
cHao

Reputation: 86506

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

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

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816242

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

var number = +str.substr(1);

Upvotes: 0

Kon
Kon

Reputation: 27431

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

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

Upvotes: 2

Related Questions