2015-05-14 93 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);