2015-05-14 100 views
0

我知道JavaScript的分割例程。我在这种模式下有一个字符串Employee - John Smith - Director按字符串中的第一个连字符分割字符串

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

来源:Employee
子:John Smith - Director

+1

http://stackoverflow.com/questions/4607745/split-string-only-on-first-instance-of-specified-character – Manube

+0

使用匹配的可能,而不是重复的分裂https://regex101.com/r/mT0iE7/23 –

回答

1
var str = "Employee - John Smith - Director " 
str.split("-",1) 

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

+2

这将返回“员工”,没有别的。你测试了你的代码吗? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Parameters – Kobi

+0

是的,我在做。这里是我的代码var res = str.split(“ - ”,1); – User089

1

我会用正则表达式:

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

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

+0

其清洁和良好的解决方案 –

1

你可以像

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