2

I know the split routine of JavaScript. I've a string in this pattern Employee - John Smith - Director.

I want to split it on the base of first hyphen using JavaScript and it'll seem like:

Source: Employee
Sub: John Smith - Director

tjati
  • 5,453
  • 3
  • 35
  • 54
User089
  • 139
  • 3
  • 13

3 Answers3

3

I would use a regular expression:

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

So you have in c[0] the first word and in c[1] the rest.

tjati
  • 5,453
  • 3
  • 35
  • 54
2
var str = "Employee - John Smith - Director "  
str.split("-",1)

Then to split other use this link: How can I split a long string in two at the nth space?

Community
  • 1
  • 1
Ankita
  • 628
  • 1
  • 8
  • 22
  • 2
    This returns "Employee " and nothing else. Did you test your code? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Parameters – Kobi May 14 '15 at 10:33
  • Yes, I'm doing. here is my code var res = str.split(" - ", 1); – User089 May 14 '15 at 10:36
2

you can do like

var str = "Employee - John Smith - Director "  
var s=str.split("-");
s.shift() ;
s.join("-");
console.log(s);
Roli Agrawal
  • 2,186
  • 3
  • 21
  • 27