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
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
- 1 probable duplicate of stackoverflow./questions/4607745/… – Manube Commented May 14, 2015 at 10:33
- use match instead of split regex101./r/mT0iE7/23 – Avinash Raj Commented May 14, 2015 at 10:42
4 Answers
Reset to default 3I 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.
you can do like
var str = "Employee - John Smith - Director "
var s=str.split("-");
s.shift() ;
s.join("-");
console.log(s);
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?
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"]