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
    `/` designates the opening and closing of regex literal syntax. There's no need for it when building the regex from a string. – cookie monster Jun 17 '14 at 01:54
  • ...and I'm not sure what you're trying to do with `return replacedString = `. Is `replacedString` a variable that is used somewhere? – cookie monster Jun 17 '14 at 01:56
  • @cookie monster first I saved the result in a var. But then I decided to just return it directly. My fault. Now I've corrected it in my question. – Faiz Ahmed Rana Jun 17 '14 at 02:21

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
  • 34,836
  • 16
  • 72
  • 77
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,823
  • 1
  • 16
  • 31