简体   繁体   中英

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...

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM