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.
4
  • 3
    Javascript strings are immutable. Calling replaceAll without assignment is useless. Commented Jun 14, 2021 at 17:37
  • Also, see this demo. Commented Jun 14, 2021 at 17:42
  • 1
    @ASDFGerte But this is not the only problem why this does not work. Commented Jun 14, 2021 at 17:55
  • No, indeed not, but i also never said it would be. Commented Jun 14, 2021 at 20:42

3 Answers 3

4

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);

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

1 Comment

Awesome, It's work. I used to try this but forget to re assign message!!! Thank you.
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.

3 Comments

thank for your help. The fourth bird's way is what I need and simple for me :)
@thepnguyennhu No problem. The advantage of my answer is that it has recursion mitigation. Try values = ['zero', '{3}', 'two', 'three']; with mine and with theirs to see what I mean.
yep, to make sure is existed in values
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.

Comments

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.