2

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.

3
  • The above code is invalid syntax. Commented Dec 19, 2012 at 16:53
  • Pardon me for the syntax errors. It could be a typo. But this is teh logic that i use in a bigger chunk of code. Commented Dec 19, 2012 at 16:57
  • Also, there is no syntax error on the Regex, which is the core answer i want Commented Dec 19, 2012 at 16:57

4 Answers 4

2

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>"
Sign up to request clarification or add additional context in comments.

Comments

1

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)];
});

Comments

1

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);

9 Comments

str.replace("${" + i + "}", list[i]);
this would repalce only one instance. I went in for the regex, coz i need to replace all instaces in the text.
@Raghav Use this: str.replace(new RegExp("${" + i + "}", "g"), list[i]);.
sorry @Vision this is not replacing any text
Because for regexes to work you have to make sure you escape every single symbol with regex meaning. Here, though, any string is fine.
|
1
    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)];
    });
}

2 Comments

Thanks. Can u pls do the replace with list[i]? list being string array. list[i] = "${conference name}"
Edited! Also see the fiddle!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.