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...
-
so you basically want all integers after 0COLD TOLD– COLD TOLD2012-07-19 05:20:49 +00:00Commented Jul 19, 2012 at 5:20
-
Does your structure contains only COR*****?micnic– micnic2012-07-19 05:22:18 +00:00Commented Jul 19, 2012 at 5:22
-
no, there will be other like MCR,TCP,VCF...Basim Sherif– Basim Sherif2012-07-19 05:26:49 +00:00Commented Jul 19, 2012 at 5:26
-
if only 3 letters then you need refp's answermicnic– micnic2012-07-19 05:30:41 +00:00Commented Jul 19, 2012 at 5:30
Add a comment
|
2 Answers
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);
6 Comments
bugwheels94
what if he has CORE instead of COR
Filip Roséen
@AnkitGautam I'm about to write an edit answering just that, hold on.. but according to the post it seems as if it's always three characters. but as said, hold on.
Basim Sherif
Hey that is exactly what I am looking for. There will be no "CORE" all of the combination will have only 3 letters. Thanks refp :)
Basim Sherif
Can you tell me why we use console.log(n) here?
micnic
console.log() shows the result in the browser's console, like google chrome's inspect element or firebug
|
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
1 Comment
Filip Roséen
this doesn't follow the description posted by OP, also; why would you use parseFloat when parseInt will be sufficient - and OP requested an integer?