2

My code only replaces the first match, ignoring the flags (global and multi line). What am I doing wrong?

for (var i = 0; i < values.length; i++) {
        template = template.replace('{' + i + '}', values[i].toString().trim(), 'gm');
    }

As you can see, my placeholders have this format: {0}, {1} etc

1
  • Unless there's some new feature I don't know about, the .replace() method doesn't accept regex modifiers. Maybe you meant to use the RegExp constructor? Commented Jul 11, 2013 at 20:02

1 Answer 1

5

According to MDN, the flags are non-standard for the normal .replace() method. Instead, you can pass in a RegExp with the same result.

template.replace(new RegExp('\\{' + i + '\\}', 'gm'),
    values[i].toString().trim());

Since curly braces have special significance in regular expressions, you have to escape them.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, it turns out this RegEx doesn't work at all. This string: <input type="text" name="Name" value="{1}" /> is returned as: <input type="text" name="Name" value /> Can anyone fix it? I think RegEx is evil myself, I hate it :-)
@TerjeHauger: I don't see how that's possible, the regex isn't even capturing = or ". What was the value of values[i].toString()?
var test = "<label>Active:</label><input type="checkbox" name="Active"{10} />"; document.write(test.replace(new RegExp('\\{1\\}', 'gm'), '')); Output: <input type="checkbox" name="Active" =""=""> Huh?!
Now I get it. This html: <.. name="Name"{0} /> is recognized as an html attribute, and at least in Chrome, {0}="" is added automagically. My idea was to insert 'checked="checked" based on passed value. I guess I should try a different template placeholder, <% %> will probably work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.