Benn Benn - 2 months ago 7
Javascript Question

String replace multiple strings trouble with 1 and 10

I am trying to replace multiple words/strings in a string and tested all suggested solutions here
Replacing 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.

Answer

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>