0

Currently I am trying to make a function in JavaScript that takes three arguments;
1. Template String
2. Word To Replace
3. Word To Replace With

Here's what I tried:

function replaceAll(templateString, wordToReplace, replaceWith)
{
    var regex = new RegExp("/" + wordToReplace + "/","g");
    return templateString.replace(regex, replaceWith);
}

console.log(replaceAll('My name is {{MyName}}', '{{MyName}}', 'Ahmed'));

But it's still giving me the templateString back. Without replacing.
This is what I got back: My name is {{MyName}}

2 Answers2

0

Here's a way without using Regex.

var replaceAll = function(tmpString, wordToReplace, wordToReplaceWith){
  return tmpString.split(wordToReplace).join(wordToReplaceWith);
}

replaceAll(str, '{{MyName}}', 'Ahmed'); //    "My name is Ahmed"
Tyler McGinnis
  • 33,715
  • 16
  • 71
  • 75
0

Your code is correct, except you don't need the beginning and ending '/' when using the class RegExp:

function replaceAll(templateString, wordToReplace, replaceWith)
{
    var regex = new RegExp(wordToReplace,"g");
    return replacedString = templateString.replace(regex, replaceWith);
}

console.log(replaceAll('My name is {{MyName}}', '{{MyName}}', 'Ahmed'));
stephenspann
  • 1,733
  • 1
  • 14
  • 31