简体   繁体   中英

How to replace two curly brackets with strings?

I want to turn this: 'text {n} text {2} text' into this 'text first text second text'

I thought it was easy:

function setLocales (string, first, second) {
  string.replace(/\{(.+?)\/(.+?)\}/g, function (first, label second) {
    // What to do here?
  }
  return string
}

// usage: setLocales(string, 'first', 'second')

But I was wrong. And I'm stuck in the middle of the function.

How to complete this function?

There is an example of using a function with String.prototype.replace on MDN site . Your callback function parameters are wrong; the first parameter is the whole matched substring (matched by the whole regex).

The easiest and most reliable way would be to match one "{something}" at a time and loop for each replacement you have in store:

/* Pseudo */
for (let replacement of ['first', 'second']) {
    str.replace("{.*}", replacement);
}

As replace targets the first find, you can use it like that:

 function setLocales(s) { for (var i = 1; i < arguments.length; i++) { s = s.replace(/{.+?}/, arguments[i]); } console.log(s); } setLocales('text {n} text {2} text', 'first', 'second'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM