0

I have a string like this:

Please enter {0}, or {1} and {0}, maybe we have {2} or event {3}.

Of course I have an array hold the value with corresponding index like:

const values = ['zero', 'one', 'two', 'three']

I try to replace all the pattern {number} with many ways, the code below is one of them but it still haven't work:

for (let i = 0; i < values.length; i++) {
    const regex = new RegExp(`\\b{${i}}\\b`, 'g')
    message.replaceAll(regex, values[i])
  }

Expected result:

Please enter zero, or one and zero, maybe we have two or event three.

3 Answers3

3

Creating a regex using const regex = new RegExp(\\b{${i}}\\b, 'g') will generate a regex like /\b{0}\b/ and is not a valid expression.

Also, you are not overwriting the value of message, and you do not need a new RegExp to do the replacements.

You can use the counter between the curly braces to get the string to replace using {${i}}

let message = "Please enter {0}, or {1} and {0}, maybe we have {2} or event {3}.";
const values = ['zero', 'one', 'two', 'three']
for (let i = 0; i < values.length; i++) {
  message = message.replaceAll(`{${i}}`, values[i])
}
console.log(message);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

You need to make use of .replace()'s anonymous callback.

// The text
var message = `Please enter {0}, or {1} and {0}, maybe we have {2} or {6} event {3}.`;

// Our replacements, make them global with var
var values = ['zero', 'one', 'two', 'three'];

// Capture desired content and save the digits into its own capture group
console.log( message.replace( /\{(\d+)\}/g, function(matches, dollar_one){
  
  // If we have a replacement then return it
  if(values[dollar_one]){
    return values[dollar_one];
  }
  // Otherwise return the whole match. {6} from the example above
  else{
    return matches;
  }
}));

Output

Please enter zero, or one and zero, maybe we have two or {6} event three.
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
1

Similar to @MonkeyZeus here is another way to use anonymous replacer in .replace(/re/, replacer):

const message = `Please enter {0}, or {1} and {0}, maybe we have {2} then event {6}/{5} and {3}.`;

// Our replacements
var values = ['zero', 'one', 'two', 'three'];

// match {digits} and replace with values[index]
var r = message.replace(/{(\d+)}/g, (m, g1) => 
        g1 in values ? values[g1] : m);

console.log(r);
//=> Please enter zero, or one and zero, maybe we have two then event {6}/{5} and three.
anubhava
  • 761,203
  • 64
  • 569
  • 643