0

I want to replace number with special characters and numbers from a string.

Ex."3 6 8 47" and expected output is " $3 $6 $8 $47 ".

I can use replace method and implemented like below:

var content = "1 3 4";
content = content.replace(/1/g, " $1 ");
console.log(content); // $1 3 4

Here, I can replace only one number and I do want to write for each number.

Or I can use split method and add $ to each items of array and join.

I'm looking for some generic replace method to achieve this.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Ranjit Kumar
  • 273
  • 3
  • 16

2 Answers2

8

You can use \d+ to match one or more digits. Inside replacement part, $& will refer to the matched string. As $ has special meaning in regex replacement part, to show $ as literal, you need to use $$.

.replace(/\d+/g, '$$$&')

console.log('1 2 3'.replace(/\d+/g, '$$$&'));

More info on MDN

Tushar
  • 85,780
  • 21
  • 159
  • 179
1

As an alternative, you can use the callBack of replace function if you want. It would give you a provision to modify the matched string even more.

let replaced = "3 6 8 47".replace(/\d+/g, (str) => ("$" + str));
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130