Search code examples
javascriptlodash

javascript replace function not returning new value


The task is simple. I wrote a function that is expected to replace the string from an identifier and array of object().

var replacer = function(original, replacement) {
     console.log(replacement)
        _.each(replacement, (value, key) => {
            original =  original.replace('${' + key+'}', value)
        });
        return original;    
}

console.clear();


var asString = "This is my email ${email} & ${mobile}";
var replacement = {"email":"[email protected]", "mobile":"999999999"}
asString = replacer(asString, replacement);
console.log(asString) // Here i am getting it properly replaced


var replacement ={"email":"[email protected]", "mobile":"0000000"}
asString2 = replacer(asString, replacement);
console.log(asString2) // Here i am still getting old value not new value

http://jsfiddle.net/1gc9xka8/

if you check the update one, http://jsfiddle.net/1gc9xka8/1

I even changed the variable but still i get the old value.

Kindly advise what is wrong here.


Solution

  • You are passing the replaced string instead of original string

    var replacer = function(original, replacement) {
      console.log(replacement)
      _.each(replacement, (value, key) => {
        original = original.replace('${' + key + '}', value)
      });
      return original;
    }
    
    console.clear();
    var asString = "This is my email ${email} & ${mobile}";
    var replacement1 = {
      "email": "[email protected]",
      "mobile": "999999999"
    };
    var asStringReplacement1 = replacer(asString, replacement1);
    console.log(asStringReplacement1);
    var replacement2 = {
      "email": "[email protected]",
      "mobile": "0000000"
    };
    var asStringReplacement2 = replacer(asString, replacement2);
    console.log(asStringReplacement2);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>