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

regex - How to split a string on the first occurrence of one of multiple substrings in JavaScript? - Stack Overflow

programmeradmin1浏览0评论

Given strings

s1 = "abcfoodefbarghi" 

and

s2 = "abcbardefooghi"

How can I split s1 into "abc" and "defbarghi" and s2 into "abc" and "defooghi" That is: split a string into two on the first occurrence of either one of strings "foo" or "bar"

I suppose this could be done with s.split(/regexp/), but what should this regexp be?

Given strings

s1 = "abcfoodefbarghi" 

and

s2 = "abcbardefooghi"

How can I split s1 into "abc" and "defbarghi" and s2 into "abc" and "defooghi" That is: split a string into two on the first occurrence of either one of strings "foo" or "bar"

I suppose this could be done with s.split(/regexp/), but what should this regexp be?

Share Improve this question edited Sep 23, 2011 at 12:20 Marek Miettinen asked Sep 23, 2011 at 10:09 Marek MiettinenMarek Miettinen 3991 gold badge7 silver badges18 bronze badges 1
  • Look at this question: Split string once in javascript – Jan Pfeifer Commented Sep 23, 2011 at 10:32
Add a ment  | 

2 Answers 2

Reset to default 3

Use a Regular Expression in this way:

var match = s1.match(/^([\S\s]*?)(?:foo|bar)([\S\s]*)$/);
/* If foo or bar is found:
  match[1] contains the first part
  match[2] contains the second part */

Explanation of the RE:

  • [\S\s]*? matches just enough characters to match the next part of the RE, which is
  • (foo|bar) either "foo", or "bar"
  • [\S\s]* matches the remaining characters

Parentheses around a part of a RE creates a group, so that the grouped match can be referred, while (?:) creates a non-referrable group.

str.replace(/foo|bar/,"\x034").split("\x034")

idea is replace the first occurrence with a special(invisible) String, and then split against this string.

发布评论

评论列表(0)

  1. 暂无评论