3

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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works and is well explained. In the end I needed to match the last occurrence and get the splitting string back, so I did /^([\S\s]*)(foo|bar)([\S\s]*?)$/. Thank you.
2
str.replace(/foo|bar/,"\x034").split("\x034")

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.