-1

I have the following code, guess what the string doesn't get replaced for some reason, if I try manually agreements.replace('{customername}', 'some string'); everything works fine.

  var keywords = [
    {
      key: '{customername}',
      desc: 'Customer Name',
      map: 'user_name'
    },

    {
      key: '{vesselname}',
      desc: 'Customer Vessel Name',
      map: 'vessel_name'
    }
  ];

  var parseData = {
    user_name: "Some name",
    vessel_name: "Some Vessel",
    spot_title: "My Spot",
    today: new Date().toDateString()
  };

  var agreements = "{customername}, some customer, {vesslname} -> here";

  for(var i = 0; i < keywords.length; i++) {
    console.log(keywords[i]['key'], parseData[keywords[i]['map']]);

    agreements.replace(
        keywords[i]['key'],
        parseData[keywords[i]['map']]
    );
  }

  alert(agreements);

Please ignore I'm adding some more detail, well stackoverflow makes it a requirement, interesting...

dud3
  • 409
  • 1
  • 6
  • 16
  • `.replace` returns new string and does not replaces original string. Just assign it back – Rajesh Oct 29 '16 at 11:38
  • @Rajesh Oh come on, huh. =) – dud3 Oct 29 '16 at 11:39
  • @Rajesh thanks, that just worked. – dud3 Oct 29 '16 at 11:41
  • Its alright. Also, I have requested to delete the answer. Once done, please delete the question as it will not add much to portal – Rajesh Oct 29 '16 at 11:46
  • Sure. Is js inconsistent? at least it seems like that to me, sorting an array does change the actual array, such as: `arr = [3, 2, 1]; arr.sort(); console.log(arr);` outputs: `[1, 2, 3]`, but `str = "a b c"; str.replace('a', 'z');` doesn't change the original variable. – dud3 Oct 29 '16 at 14:03
  • Or maybe it's trying to be optimized when it comes to arrays, so it passes them by reference instead by value? – dud3 Oct 29 '16 at 14:07
  • If you consider Java, `List` are mutable but string is **immutable**. So when you do `String a = "123"; String b = "456"; String c=a+b;` this simple expression will create around 7 object of string. So its not just JS but its a consistent behaviour across all major languages. – Rajesh Oct 29 '16 at 14:39
  • An interesting article: http://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript – Rajesh Oct 29 '16 at 14:40

1 Answers1

0

change code to this:

  agreements = agreements.replace(
        keywords[i]['key'],
        parseData[keywords[i]['map']]
    );
Sam
  • 1,424
  • 13
  • 28
  • Just a pointer, you should not answer question with obvious mistake. Rather search post that has already answered it and share its link. Soon, you will get rights to vote to close. Once you have them, just mark it as duplicate. Also if its not much trouble, please delete the answer. I know its not wrong, but there is no need for this question. – Rajesh Oct 29 '16 at 11:44