Replacing string match with a callback function

suggest change

String#replace can have a function as its second argument so you can provide a replacement based on some logic.

"Some string Some".replace(/Some/g, (match, startIndex, wholeString) => {
  if(startIndex == 0){
    return 'Start';
  } else {
    return 'End';
  }
});
// will return Start string End

One line template library

let data = {name: 'John', surname: 'Doe'}
"My name is {surname}, {name} {surname}".replace(/(?:{(.+?)})/g, x => data[x.slice(1,-1)]);

// "My name is Doe, John Doe"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents