简体   繁体   English

如何在JavaScript中多个子串中的一个子串上拆分字符串?

[英]How to split a string on the first occurrence of one of multiple substrings in JavaScript?

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" 如何将s1拆分为“abc”和“defbarghi”,将s2拆分为“abc”和“defooghi”即:在第一次出现字符串“foo”或“bar”时将字符串拆分为两个

I suppose this could be done with s.split(/regexp/) , but what should this regexp be? 我想这可以用s.split(/regexp/) ,但这个正则表达式应该是什么?

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: RE的解释:

  • [\\S\\s]*? matches just enough characters to match the next part of the RE, which is 匹配足够的字符以匹配RE的下一部分,即
  • (foo|bar) either "foo", or "bar" (foo|bar) “foo”或“bar”
  • [\\S\\s]* matches the remaining characters [\\S\\s]*匹配剩余的字符

Parentheses around a part of a RE creates a group, so that the grouped match can be referred, while (?:) creates a non-referrable group. RE的一部分周围的括号创建一个组,以便可以引用分组的匹配,而(?:)创建一个不可引用的组。

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

idea是用特殊的(不可见的)String替换第一个匹配项,然后对该字符串进行拆分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM