How can I extract "456" from "xxx_456" where xxx is of indefinite length?
+2
A:
The substring method allows you to specify start and end index:
var str = "xxx_456";
var subStr = str.substring(str.length - 3, str.length);
Darin Dimitrov
2010-03-08 09:30:55
+1
A:
alert("xxxxxxxxxxx_456".substr(-3))
caveat: according to mdc, not IE compatible
stereofrog
2010-03-08 09:31:58
but `slice` is - see my answer.
Andy E
2010-03-08 09:58:35
+6
A:
var str = "xxx_456";
var str_sub = str.substr(str.lastIndexOf("_")+1);
If it is not always three digits at the end (and seperated by an underscore). If the end delimiter is not always an underscore, then you could use regex:
var pat = /([0-9]{1,})$/;
var m = str.match(pat);
Psytronic
2010-03-08 09:32:06
+1 lastIndexOf is exactly what you want here, faster than regex and more flexible than substr.
Phil H
2010-03-08 09:35:51
@Phil: not measurably faster, unless it's being called thousands of times. You'd need to call them millions of times before the difference would be noticeable.
outis
2010-03-08 09:47:02
could also be 'xxx_456'.match(/_.+$/)[0] or 'xxx_456'.replace(/(^.+_)(.+$)/,'$1')?
KooiInc
2010-03-08 09:40:27
@Kooilnc: No need to overcomplicate regexes just because you can. Your first example would also match the `_`.
Andy E
2010-03-08 10:07:12
@Andy E: you're right about the _. Second possibility: $1 should be $2 by the way.
KooiInc
2010-03-08 12:17:37
+2
A:
you can just split it up and get the last element
var string="xxx_456";
var a=string.split("_");
alert(a[1]); #or a.pop
ghostdog74
2010-03-08 09:38:42
+1, I would have provided the split-pop method in my own answer if you hadn't mentioned it :-)
Andy E
2010-03-08 10:04:50
+1
A:
slice works just fine in IE and other browsers, and it's probably the most efficient method too:
alert("xxx_456".slice(-3));
slice Method (String) - MSDN
slice - Mozilla Developer Center
And there's the regex option:
alert("xxx_456".match(/\d+$/))[0];
Andy E
2010-03-08 09:55:28
+1
A:
here is my custom function
function reverse_substring(str,from,to){
var temp="";
var i=0;
var pos = 0;
var append;
for(i=str.length-1;i>=0;i--){
//alert("inside loop " + str[i]);
if(pos == from){
append=true;
}
if(pos == to){
append=false;
break;
}
if(append){
temp = str[i] + temp;
}
pos++;
}
alert("bottom loop " + temp);
}
var str = "bala_123";
reverse_substring(str,0,3);
This function works for reverse index.
coder
2010-03-08 10:13:33
+1
A:
Simple regex for any number of digits at the end of a string:
'xxx_456'.match(/\d+$/)[0]; //456
'xxx_4567890'.match(/\d+$/)[0]; //4567890
or use split/pop indeed:
('yyy_xxx_45678901').split(/_/).pop(); //45678901
KooiInc
2010-03-08 12:22:55