Javascript 带有反向索引的子串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2400312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Substring with reverse index
提问by Ricky
How can I extract "456" from "xxx_456" where xxx is of indefinite length?
如何从“xxx_456”中提取“456”,其中 xxx 长度不定?
回答by Andy E
sliceworks just fine in IE and other browsers, it's part of the specification and it's the most efficient method too:
slice在 IE 和其他浏览器中工作得很好,它是规范的一部分,也是最有效的方法:
alert("xxx_456".slice(-3));
//-> 456
slice Method (String) - MSDN
slice - Mozilla Developer Center
回答by Psytronic
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);
回答by Darin Dimitrov
回答by ghostdog74
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
回答by user187291
回答by KooiInc
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:
或确实使用 split/pop:
('yyy_xxx_45678901').split(/_/).pop(); //45678901
回答by nf071590
String.prototype.reverse( ) {
return Array.prototype.slice.call(this)
.reverse()
.join()
.replace(/,/g,'')
}
using a reverse string method
使用反向字符串方法
var str = "xxx_456"
str = str.reverse() // 654_xxx
str = str.substring(0,3) // 654
str = str.reverse() //456
if your reverse method returns the string then chain the methods for a cleaner solution.
如果您的反向方法返回字符串,则链接方法以获得更清洁的解决方案。
回答by Mahfuzur Rahman
Also you can get the result by using substringand lastIndexOf-
您也可以通过使用substring和获得结果lastIndexOf-
alert("xxx_456".substring("xxx_456".lastIndexOf("_")+1));
回答by YOU
A crazy regex approach
一个疯狂的正则表达式方法
"xxx_456".match(/...$/)[0] //456
回答by coder
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.
此功能适用于反向索引。

