Regular expression matches an extra empty group
javascript, regex
Solution
You are getting that last false-positive match because your regular expression is matching empty strings:
"".replace(/(.*?)(?:_(\d))?(?:,|$)/g, "title: '$1' ('$2') ");
title: '' ('')
So, in your case after all characters have been consumed, it will match an empty string.
You can control by changing your first group to be non-optional, considering it is not really an optional one as it shows.
/(.*?)(?:_(\d))?(?:,|$)/g
--^^--
For example,
var str = "test_1,some_2,foo,bar_4";
test.replace(/([a-z]+)(?:_(\d))?(?:,|$)/gi, "title: '$1' ('$2') ");
title: test (1) title: some (2) title: foo () title: bar (4)
That is,
- `([a-z]+)`: Matching at least one alphabetical character, and
- `gi`: Making the string case-insensitive.
Problem
I'm new to the domain of regular expressions. All I'll post below are simplified examples from my code. I have a string, let's say `test_1,some_2,foo,bar_4,` that I want to replace by `title: test (1) title: some (2) title: foo () title: bar (4)` What I have now is (which works): ``` var test = "test_1,some_2,foo,bar_4,"; console.log(test.replace(/(.*?)(?:_(\d))?,/g, "title: $1 ($2)\n")); ``` which outputs: ``` title: test (1) title: some (2) title: foo () title: bar (4) ``` In an effort to makes things right, I want to get rid off the coma after the last item. The list will look like `test_1,some_2,foo,bar_4` (no coma after bar_4) So the new code: ``` var test = "test_1,some_2,foo,bar_4"; console.log(test.replace(/(.*?)(?:_(\d))?(?:,|$)/g, "title: $1 ($2) ")); ``` outputs something wrong. There's an extra empty match at the end: ``` title: test (1) title: some (2) title: foo () title: bar (4) title: () ``` My questions are: Why? How to fix it? Is there any possible improvements in the actual regex? demo jsFiddle