0

the new_data output is ",$,2,$,4,$,"

but I am expecting ",$,$,$,$,$,", can someone kindly explain why to me? Thanks.

var data = ",1,2,3,4,5,";
var pattern = /,\d,/g
var new_data = data.replace(pattern, function(match){
  return ",$,";
});
console.log(new_data);

2 Answers 2

3

Because ,\d, eats up ,1, . Then the regex engine tries to match the next ,\d,, since the first pattern eats up the , which exists before 2 , ,2, wouldn't be visible to the regex engine. Likewise the same happens for 4.

So you could use positive lookahead.

string.replace(/,\d(?=,)/g, ",$")

Here the second comma won't be matched since lookarounds are assertions which won't capture any single character.

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

2 Comments

if I use ?: even if it doesn't capture the ",", it still eat up ",", seem only ?= lookahead not eating up any character, nice to know something new about regex, thanks @avinash-raj
yes (?:) (non-capturing group) should match the character .
2

You can solve this by removing the last comma

/,\d/g

The problem is that the second comma is being consumed by the first match.

Example:

,1,2,3,4,5

Match 1: ,1,
,2, is not a match because the first comma is consumed by Match 1

Mathc 2: ,3,
,4, is not a match because the first comma is consumed by Match 2

2 Comments

but this would slihtly modify the meaning of the pattern. It would match, if it ends wiht ,5, not only if it ends with ,5,
Yes you are right, but I am going to keep my answer because the OP might find this useful. Thank you for your comment @dognose

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.