0

According to this, "If separator is a regular expression that contains capturing parentheses (), matched results are included in the array." To me, that's an unwanted side effect. I would like to split on a \n or a <br> string, and I don't know how to do this without using parentheses around it:

string.split(/(\n|\<br\>)/)

is there a way of writing this regex without parentheses? I don't want to include the separators in the result. Here's an example of it working incorrectly:

console.log("hi\nbye<br>foo".split(/(\n|\<br\>)/))
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • See [What is a non-capturing group in regular expressions?](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions) – Wiktor Stribiżew Jan 12 '21 at 22:36
  • 1
    Just remove the parentheses ?? – CertainPerformance Jan 12 '21 at 22:36
  • 1
    Dupe of [javascript regex split produces too many items](https://stackoverflow.com/questions/17516040/javascript-regex-split-produces-too-many-items) – Wiktor Stribiżew Jan 12 '21 at 22:37
  • @CertainPerformance yep. I feel like an idiot. Aren't there certain situations where you have to wrap parens around an "or"? Did I just imagine that? – Daniel Kaplan Jan 12 '21 at 22:38
  • @WiktorStribiżew I agree. – Daniel Kaplan Jan 12 '21 at 22:39
  • Sure, eg: `a(b|c)` matches `ab` or `ac`. If in a situation like that and the capturing is a problem, use a non-capturing group instead. Generally, only use a capturing group when you *need* the capturing; use non-capturing by default when you just want logical grouping. – CertainPerformance Jan 12 '21 at 22:39
  • All right, should i just delete this, or leave it around to help people find the answer when they Google? – Daniel Kaplan Jan 12 '21 at 22:39
  • 1
    You need paranthesis around alternation (`|`) if you have something like `a(b|c)d` where you want to match either `abd` or `acd`, whereas `ab|cd` matches either `ab` or `cd`. However, in this case it's not really needed as you still have ` or ` expression. – VLAZ Jan 12 '21 at 22:40

0 Answers0