8

I don't understand why, but this code gives me a JavaScript error:

<script type="text/javascript">

String.prototype.format = function(values) {
    var result = this;
    for (var i = 0, len = values.length; i < len; i++) {
        result = result.replace(new RegExp("{" + i + "}", "g"), values[i]);
    }
    return result;
};

alert("Hi {0}, I'm {1}. Are you, {0}?".format(["Chris", "swell"]));

</script>

Error

Exception thrown: invalid quantifier

What's wrong with it?

2
  • It's like printf for JavaScript! :P Commented Aug 30, 2010 at 5:53
  • 1
    Just as a side note, you could always use the arguments variable instead of passing an array as a parameter. Commented Aug 30, 2010 at 6:29

2 Answers 2

2

I believe you have to escape the { and }.

String.prototype.format = function(values) {
    var result = this;
    for (var i = 0, len = values.length; i < len; i++) {
        result = result.replace(new RegExp("\\{" + i + "\\}", "g"), values[i]);
    }
    return result;
};
Sign up to request clarification or add additional context in comments.

Comments

1

The { and } have special meaning within a regex. They are used to specify exact quantifiers.

To treat them literally, just drop two backslashes before them like so: \\{ and \\}.

One does not work, as I just found out. It must treat one of them as regex delimiters.

Comments

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.