【问题标题】:Split a string by the first hyphen in the string按字符串中的第一个连字符拆分字符串
【发布时间】:2015-07-25 22:25:32
【问题描述】:

我知道 JavaScript 的拆分例程。我在这个模式中有一个字符串Employee - John Smith - Director

我想使用 JavaScript 在第一个连字符的基础上拆分它,它看起来像:

来源:Employee
子:John Smith - Director

【问题讨论】:

标签: javascript regex string


【解决方案1】:

我会使用正则表达式:

b = "Employee - John Smith - Director"
c = b.split(/\s-\s(.*)/g)
c    
["Employee", "John Smith - Director", ""]

所以你有c[0] 第一个词和c[1] 其余的。

【讨论】:

  • 为什么它在数组末尾返回另一个空元素?
【解决方案2】:

你可以这样做

var str = "Employee - John Smith - Director "  
var s=str.split("-");
s.shift() ;
s.join("-");
console.log(s);

【讨论】:

    【解决方案3】:
    var str = "Employee - John Smith - Director "  
    str.split("-",1)
    

    然后拆分其他使用此链接:How can I split a long string in two at the nth space?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多