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>
Exception thrown: invalid quantifier
What's wrong with it?
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With