admin管理员组文章数量:1430685
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?
- Look at this question: Split string once in javascript – Jan Pfeifer Commented Sep 23, 2011 at 10:32
2 Answers
Reset to default 3Use 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.
本文标签:
版权声明:本文标题:regex - How to split a string on the first occurrence of one of multiple substrings in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745528327a2661942.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论