Raghav
Raghav

Reputation: 3058

js regex replace multiple words

I need to replace ${conferance name} with ABC, ${conference day} with Monday in the following sentence. Could some one help me with the regex.

var text = "<td>${conference name}</td><td>${conference day}</td>"

var list = ["${conferance name}", "${conference day}" ]

for (var j = 1; j < list.length; j++) {
            //Extracting the col name
            var colName  =   list[j].split("${");
            colName = colName.split("}")[0];
            //Replacing the col name
            text = text.replace(new RegExp('\\$\\{' + colName + '\\}', 'g'), "ABC");

        }

The above code repalces fine if i have ${conference_name}, but it fails when i have a space in between.

The list is a dynamic array. And the Replace texts are also dynamic. I just simulated them as objects here for fitting them in the Regex Statement.

Thanks in Advance.

Upvotes: 2

Views: 1836

Answers (4)

maerics
maerics

Reputation: 156434

Here's a version that lets you parameterize the replacements explicitly:

function doReplace(repl, str) {
  var regexStr = Object.keys(repl).map(function(s) {
    return s.replace(/([^\w\s])/g, '\\$1');
  }).join('|');
  return str.replace(new RegExp(regexStr, 'g'), function(m) {
    return repl[m];//it changed to "repl"  
  });
}

var replacements = {
  "${conference name}": "ABC",
  "${conference day}": "Monday"
};

doReplace(replacements, text) // => "<td>ABC</td><td>Monday</td>"

Upvotes: 2

closure
closure

Reputation: 7452

    var str = "<td>${conference name}</td><td>${conference day}</td>";
    var list = ["${conference name}", "${conference day}" ];
    var listResult = ["ABC", "Monday" ];

Generic model

See it working http://jsbin.com/atehun/6/watch

Construct str, list, listResult as shown in above example.

function genericReplace(str, list, listResult) {    

    var escape = function(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    
    var escList = [];
    for (var i=0; i < list.length; i++) {
      escList.push( escape(list[i]) );
    }
    
    var regEx = new RegExp(escList.join('|'), "g");

    return str.replace(regEx, function(word) {
      return listResult[list.indexOf(word)];
    });
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

There is absolutely no need for a regex, since you know the exact string to search for.

var str = "<td>${conference name}</td><td>${conference day}</td>";
var list = {
  "conference name":"ABC",
  "conference day":"Monday"
};
var i;
for( i in list) {
  if( list.hasOwnProperty(i)) {
    str = str.replace("${"+i+"}",list[i]);
  }
}

The only catch is if you might have more than one of the placeholders in your search string, but in that case the innermost code can be:

do {
  oldstr = str;
  str = str.replace("${"+i+"}",list[i]);
} while(oldstr != str);

Upvotes: 1

VisioN
VisioN

Reputation: 145398

How about that?

var r = {
        "conference name": "ABC",
        "conference day" : "Monday"
    },
    reg = new RegExp("\\$\\{" + Object.keys(r).join("\\}|\\$\\{") + "\\}", "g"),
    str = "<td>${conference name}</td><td>${conference day}</td>";

str = str.replace(reg, function(v) {
    return r[v.substring(2, v.length - 1)];
});

Upvotes: 1

Related Questions