Confusion on regex non capturing group

Continuing the discussion from freeCodeCamp Challenge Guide: Spinal Tap Case:
I am finding it hard to understand why did we use ( ?: ) in .split(/(?:_| )+/) in Solution 2 and not in Solution 3. I am testing it on the (“This Is Spinal Tap”) case, and I don’t understand why was there a need of non capturing grp in one and not another.
These are two snippet of codes

function spinalCase(str) {
  str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
   return str
    .split(/(?:_| )+/)
spinalCase("This Is Spinal Tap");
function spinalCase(str) {

  return str

From MDN:

“It [non-capturing group] acts like the grouping operator in JavaScript expressions, and unlike capturing groups, it does not memorize the matched text, allowing for better performance and avoiding confusion when the pattern also contains useful capturing groups.”

There wasn’t a need. You could use either here. But I suppose if you are trying to eek out every bit of performance in your code then you would use non-capturing groups everywhere you didn’t need to reference the matched text. To be honest, I almost never use them. But I suppose in more complex expressions they can come in handy.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.