AhammadaliPK
AhammadaliPK

Reputation: 3548

how to replace all numbers in a string with a number plus a special character?

I have a string like this ,

(1 AND 2 ) OR (2 AND 3)

I need to replace this string all numbers with a numbers + special character (like 1@,2@), the result should be like this ,

(1@ AND 2@ ) OR (2@ AND 3@), 

So I tried the following ,

var d = "(1 AND 2 ) OR (2 AND 3)"
console.log(d.replace(/[0-9]/g, "@"))

but it will only produce a result like ,

(@ AND @ ) OR (@ AND @)

my expected output is ,

(1@ AND 2@ ) OR (2@ AND 3@)

Upvotes: 0

Views: 98

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Try including the match in the output with $&:

const str = '(1 AND 2 ) OR (2 AND 3)'
console.log(str.replace(/\d/g, '$&@'));

You could also use (new) lookbehind, that way the boundary is matched, but not the number itself:

const str = '(1 AND 2 ) OR (2 AND 3)'
console.log(str.replace(/(?<=\d)/g, '@'));

Upvotes: 5

Related Questions