2

I have a string, in which I am doing replace operation with the help of regex.It is done, in order to replace the particular character in the string, if that exists and to retain others.

var text = "abcdef";

var text = ((text.replace(/a/g, '1')) + (text.replace(/b/g, '2')) + (text.replace(/c/g, '3')));

Expected Output: 123def

But I am getting the output like this: 1bcdefa2cdefab3def

0

1 Answer 1

1

Your code does not work because you are concatenating the replace instead of chaining them.

var text = "abcdef";

var text = text.replace(/a/g, '1').replace(/b/g, '2').replace(/c/g, '3');
console.log(text);

However the recommended way is to use a single replace for it.

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

3 Comments

Thanks. It worked!
@srikha you could do var text = text.replace(/abc/g, '123')
@srikha but if abc can occur at random places separately then use separate replace()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.