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

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

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

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


当前回答

var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);

其他回答

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

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

var the_string = "sometext-20202";
var parts = the_string.split('-', 2);

// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'

var the_text = parts[0];
var the_num  = parts[1];

我会怎么做:

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

我更喜欢的解决方案是:

const str = 'sometext-20202';
const slug = str.split('-').pop();

你的结果是什么

myString.split('-').splice(1).join('-')