最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split a string by the first hyphen in the string - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited May 14, 2015 at 10:39 tjati 6,0875 gold badges46 silver badges61 bronze badges asked May 14, 2015 at 10:29 User089User089 1393 silver badges14 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 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.

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"]

发布评论

评论列表(0)

  1. 暂无评论