0

there is a string and RegExp:

var str = "a1c a23c a456c 123";
var re = /a(\d*)c/g;

I want to match all number between a and c, and replace it to b, the result I would like is:

"abc abc abc 123"

how to do it?

1
  • Your regex would also match "ac" with no number - is that deliberate? Commented Feb 22, 2017 at 5:40

2 Answers 2

3

Try this

    var str = "a1c a23c a456c 123";
    var re = /(a)(\d*)(c)/g;
    
    console.log(str.replace(re, '$1b$3'));

EDIT:

If ac should not become abc, then regex should be /(a)(\d+)(c)/g

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

3 Comments

This would also replace "ac" with "abc".
If we don't want to, then regex should be /(a)(\d+)(c)/g
No need of capturing group as both characters are static.
2

Try this:

var str = "a1c a23c a456c 123";
var newStr = str.replace(/\ba\d+c\b/g, "abc");
console.log(newStr);

1 Comment

No need of capturing group /\ba\d+c\b/g, 'abc'.

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.