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,761
  • 4
  • 41
  • 56
User089
  • 139
  • 3
  • 14

4 Answers4

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,761
  • 4
  • 41
  • 56
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,356
  • 3
  • 23
  • 28
1
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
  • 621
  • 2
  • 9
  • 25
  • 3
    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
0

The question is quite old, but I wasn't super satisfied with the existing answers. So here is my staight-forward and easy-to-read solution:

const splitAtFirstOccurence = (string, pattern) => {
  const index = string.indexOf(pattern);
  return [string.slice(0, index), string.slice(index + pattern.length)];
}

console.log(splitAtFirstOccurence('Employee - John Smith - Director', ' - '));
// ["Employee", "John Smith - Director"]
Ricki-BumbleDev
  • 1,698
  • 1
  • 16
  • 18