0

I am trying to replace multiple words/strings in a string and tested all suggested solutions here How to replace all occurrences of a string in JavaScript?

They all worked until I had to replace color_1 and color_10 at the same time. Now the color_10 replacement is part of color_1 with 0 at the end.

https://jsfiddle.net/fqqLdxkz/1/

string = 'padding:0px 0px 0px 0px;margin:0px auto 0px auto;background-color:color_9;color_1;color_5;color_4;color_10;';
var palettes = {
  "theme": "{\"color_1\":\"#454545\",\"color_2\":\"#40b1e2\",\"color_3\":\"#efefef\",\"color_4\":\"#fafafa\",\"color_5\":\"#cccccc\",\"color_6\":\"#e91e63\",\"color_7\":\"#e91e63\",\"color_8\":\"#e74c3c\",\"color_9\":\"#2c3e50\",\"color_10\":\"#344957\"}"
}

function PaletteColor(css) {


  if (css.indexOf('color_') !== -1) {

    var $palette = JSON.parse(palettes.theme);

    $.each($palette, function(name, color) {
      // css = css.replace(new RegExp(name, 'g'), color);
      css = css.split(name).join(color);
    });

  }

  return css;
}
$('#result').html(PaletteColor(string));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="result">...</div>

What am I missing?

Update : tested with json reversal , color_10 first color_1 last ,
and it works https://jsfiddle.net/fqqLdxkz/2/

But it makes no sense since it looks like it is replacing indexes first than the values.

Community
  • 1
  • 1
Benn
  • 4,840
  • 8
  • 65
  • 106
  • Where are you getting stuck exactly? This is exactly what should happen; You wrote code to replace the string `color_1`, and it did exactly that. – Jake Haller-Roby Sep 17 '16 at 23:52
  • @gravityplanx, check the last replacement , it is mix from color_1 and color_10 http://prntscr.com/cj930s, should be http://prntscr.com/cj934z – Benn Sep 17 '16 at 23:56

1 Answers1

2

You could put a word-boundary assertion \b in your regex, so that color_1\b wouldn't match color_10.

var string = 'padding:0px 0px 0px 0px;margin:0px auto 0px auto;background-color:color_9;color_1;color_5;color_4;color_10;';
var palettes = {
  theme: {"color_1":"#454545","color_2":"#40b1e2","color_3":"#efefef","color_4":"#fafafa","color_5":"#cccccc","color_6":"#e91e63","color_7":"#e91e63","color_8":"#e74c3c","color_9":"#2c3e50","color_10":"#344957"}
}

function paletteColor(css) {
  if (css.indexOf('color_') !== -1) {
    var $palette = palettes.theme;

    $.each($palette, function(name, color) {
      css = css.replace(new RegExp('\\b' + name + '\\b', 'g'), color);
    });
  }
  return css;
}

$('#result').html(paletteColor(string));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="result">...</div>
4castle
  • 32,613
  • 11
  • 69
  • 106