Basim Sherif
Basim Sherif

Reputation: 5440

Split a string into two using Javascript

I have a string COR000001. I want to split it so that I get only the integer 1. If the String is like COR000555 I should get the integer 555. Thank you...

Upvotes: 1

Views: 96

Answers (2)

bkk
bkk

Reputation: 533

I had just seen some one answer this question and before i could up vote it was deleted, hence posting the solution on his behalf.

var str='COR000050ABC';
var variable=parseFloat(/[0-9]+/g.exec(str));

though there was a small modification, added parseFloat

Upvotes: 0

Filip Roséen
Filip Roséen

Reputation: 63797

The easiest method to use is to get rid of the first three characters "COR", "MCR", "TCP", etc.. and then use parseInt with the appropriate parameters such as in the below.

var str = "COR000555";
var n   = parseInt (str.substr (3), 10); // force parseInt to treat every
                                         // given number as base10 (decimal)

console.log (n);

555

If the "key" in the beginning is not always limited to three characters you could use a regular-expression to get all the digits in the end of your string.

.. as in the below;

var n = parseInt (str.match (/\d+$/)[0], 10);

Upvotes: 4

Related Questions