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

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

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

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


当前回答

我更喜欢的解决方案是:

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

你的结果是什么

其他回答

我会怎么做:

// function you can use:
function getSecondPart(str) {
    return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
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];

我更喜欢的解决方案是:

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

你的结果是什么

使用格式为\w-\d+的正则表达式,其中\w代表单词,\d代表数字。开箱即用是行不通的,所以可以试一试。试试这个。

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