在javascript字符串中的破折号后获取所有内容


149

在IE和firefox中都能做到的最干净的方法是什么。

我的字符串如下所示:sometext-20202

现在,“ sometext”和破折号后的整数可以具有不同的长度。

我应该只使用substring和index还是其他方式?

Answers:


279

我将如何做:

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

62
值得一提的是,如果字符串为,则此功能将不起作用sometext-20202-303
Istiaque Ahmed 2014年

17
@IstiaqueAhmed,可能是该问题不是专门针对非常特定的格式:“我的字符串如下:sometext-20202”
artlung 2014年

7
问题的确get everything after the dash in a string in javascript在这种情况下会失败。
Artem Kalinchuk

108

我更喜欢的解决方案是:

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

slug你的结果在哪里


1
如果使用多个定界符,则此解决方案是最好的。
Ethan Keiley

26
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];

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

6

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

您的帖子表明您已经知道如何使用substring()和进行操作indexOf(),因此我不会发布代码示例。


实际上,这是比拆分更好的解决方案,具体取决于您的应用程序,因为如果您使用多个应用程序,则可能会产生不希望的结果。
trevorgrayson

20
string.substring(string.indexOf('-')+ 1)
trevorgrayson 2013年

尽管存在polyfill,但IE8及更低版本中的indexOf不存在。
Erik Honn 2014年

3

您可以使用js中的内置RegExp(pattern [,flags])工厂符号来做到这一点:

RegExp(/-(.*)/).exec("sometext-20202")[1]

在上面的代码中,exec函数将返回一个包含两个元素([“ -20202”,“ 20202”])的数组,一个元素带有连字符(-20202),一个元素不带有连字符(20202),您应该选择第二个元素(索引1)



0

使用以下形式的正则表达式:\ w- \ d +其中\ w代表单词,\ d代表数字。他们开箱即用,所以随便玩吧。试试这个

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.