Todd Davis
Todd Davis

Reputation: 6035

JavaScript replace() seems to only grab the first hit

http://jsfiddle.net/XwHA6/

I have the string {{value}} twice in a given string. When I attempt to replace() that value, only the first instance of that value gets replaced, not the second. The JSFiddle link above demonstrates this. Is this "works as designed" or am I doing something wrong? Is there a better option?

  var str = 'Spend $ {{value}} Get $ {{value}} Off';
  var result = str.replace('{{value}}', '<a href="#" id="value" data-type="text" data-pk="1" data-name="Value" data-original-title="Amount" class="editable editable-click">value</a>');

Upvotes: 1

Views: 63

Answers (1)

Blender
Blender

Reputation: 298196

That's the default behavior of .replace() with a string argument (for some reason). Provide a regex with a global flag and it'll work:

str.replace(/{{value}}/g, ...);

Also, since I was writing one anyways, here's a simple JavaScript clone of Python's str.format:

String.prototype.format = function() {
    if (!arguments.length) {
        return this;
    }

    var mapping;

    if (typeof arguments[0] === 'object') {
        mapping = arguments[0];
    } else {
        mapping = arguments;
    }

    return this.replace(/\{(.*?)\}/g, function(match, name) {
        return mapping[name];
    });
};

You can use it like so:

str.format({value: '<a href=...'});

Or like:

'{0}{1}{0}'.format(1, 2); // "121"

Upvotes: 3

Related Questions