2

My replace all function is as below, it is in commonHelper.js file

exports.replaceAll = function (find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

Then I do following

var commonHelper = require('./commonHelper');
var html_body = commonHelper.replaceAll('[[username]]', user_row.username, template_row.message_body);
html_body = commonHelper.replaceAll('[[forgot_pass_link]]', forgot_pass_link, html_body);

this is not properly replacing the [[key]] parts here. What should I change to fix this?

3 Answers 3

6

I had to replace special characters. My updated replace all function

exports.replaceAll = function (find, replace, str) {
  var find = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  return str.replace(new RegExp(find, 'g'), replace);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use split and join as a replace all. This removes any issues with regex special characters messing up the find and replace. Example:

>> "[boo].blah.[boo].blah".split("[boo]").join("(scare)")

"(scare).blah.(scare).blah"

Comments

0

There is a replaceAll command in string module.

You might be able to use it like this in util.js:

var S=require('string');
exports.replaceAll=function(hay,rplfrom,rplto)
{
    return S(hay).replaceAll(rplfrom,rplto).s;
};

1 Comment

can't find the string module

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.