在IE和Firefox中都能工作的最干净的方法是什么?

我的字符串看起来像这个sometext-20202

现在sometext和破折号后面的整数可以有不同的长度。

我应该使用子字符串和索引还是有其他方法?


当前回答

使用内置的javascript replace()函数和使用regex(/(.*)-/),你可以用空字符串("")替换破折号之前的子字符串:

"sometext-20202".replace(/(.*)-/,""); // result --> "20202"

其他回答

我会怎么做:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));

AFAIK, Mozilla和IE都支持substring()和indexOf()。但是,请注意,某些浏览器的早期版本(特别是Netscape/Opera)可能不支持substr()。

你的文章表明你已经知道如何使用substring()和indexOf(),所以我不发布一个代码示例。

使用内置的javascript replace()函数和使用regex(/(.*)-/),你可以用空字符串("")替换破折号之前的子字符串:

"sometext-20202".replace(/(.*)-/,""); // result --> "20202"
myString.split('-').splice(1).join('-')

你可以使用分裂方法。如果你需要从特定的模式中获取字符串,你可以使用split with req。经验值:

Var string = "sometext-20202"; console.log (string.split (/-(.*)/)[ 1))