1

I have a basic replace function, but I need it to perform a global replace, as it seems to be stopping on the first instance. I do not want to do it with a Regex. Applying the global attribute seems easy enough in most examples, but I am passing in a variable as the value to be replaced, and /g is having no impact. What am I doing wrong? Here is the example without the /g:

test string

"Why is my ^%friend so ^%? Maybe I need a ^!% one, abrand^!% one"

Simple replace function

function translate(oddStr) {
    var tagDictionary = {};
        tagDictionary['^%'] = 'odd';
        tagDictionary['^!%'] = 'new';

    Object.keys(tagDictionary).forEach( function (tag) {
        oddStr = oddStr.replace(tag, tagDictionary[tag]);
    });

    return oddStr;
};

This function returns the first instance of each replaced, as expected. How can I apply /g to the tag variable in the forEach?

johnny_mac
  • 1,193
  • 3
  • 11
  • 35

3 Answers3

2

Use a split-join combo like this:

oddStr = oddStr.split(tag).join(tagDictionary[tag]);
ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61
  • I have upvoted and accepted this as my answer. My reasoning for this is that I said I wanted to do this without Regex, and this is the simplest solution. – johnny_mac Jan 28 '17 at 18:18
1
"Why is my ^% friend so ^%? Maybe I need a ^!% one, abrand ^!% one".replace(/\^%/g, 'odd').replace(/\^!%/g, 'new')

"Why is my odd friend so odd? Maybe I need a new one, abrand new one"

If you need to create the regular expression from string, you can use RegExp constructor: new RegExp('\\^%', 'g').

If you don't have control over the tag-dictionary and it is coming from some external resource, then you will have to properly escape the tags.

Instead of using adhoc symbols for templating you should ideally use something like lodash.template

Community
  • 1
  • 1
lorefnon
  • 12,112
  • 4
  • 54
  • 87
0

You need to escape your regex special characters (^=Start of string)

function translate(oddStr) {

  var tagDictionary = {
    '\\^%'  : "odd",
    '\\^!%' : 'new'
  };

  Object.keys(tagDictionary).forEach( function (tag) {
    var r = new RegExp(tag, "g");
    oddStr = oddStr.replace(r, tagDictionary[tag]);
  });

  return oddStr;
};



console.log(translate("Why is my ^%friend so ^%? Maybe I need a ^!% one, a brand ^!% one"));
Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278