Skip to content

Instantly share code, notes, and snippets.

@Cosmicist
Created March 5, 2013 04:11
Show Gist options
  • Save Cosmicist/5087928 to your computer and use it in GitHub Desktop.
Save Cosmicist/5087928 to your computer and use it in GitHub Desktop.
Simple JavaScript string formatter with possibility for custom regex
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>String format</title>
</head>
<body>
<h2>Default</h2>
<p>
<pre>Replacing &lt;strong&gt;{foo}&lt;/strong&gt; and &lt;strong&gt;{bar}&lt;/strong&gt;</pre>
<span id="format">Replacing <strong>{foo}</strong> and <strong>{bar}</strong></span>
</p>
<h2>Custom regex</h2>
<dl>
<dt>Regex</dt>
<dd>/:(\w+)/ig</dd>
<dt>Format</dt>
<dd><pre>Replacing &lt;strong&gt;:foo&lt;/strong&gt; and &lt;strong&gt;:bar&lt;/strong&gt;</pre></dd>
</dl>
<p>
<span id="custom">Replacing <strong>:foo</strong> and <strong>:bar</strong></span>
</p>
<script src="string.format.js"></script>
<script>
var el = document.getElementById('format');
el.innerHTML = el.innerHTML.format({foo: 'this', bar: 'that'});
var el = document.getElementById('custom');
el.innerHTML = el.innerHTML.format({foo: 'this', bar: 'that'}, /:(\w+)/ig);
</script>
</body>
</html>
"use strict";
(function()
{
String.prototype.format = function(reps, regex) {
if (typeof regex == 'undefined' || regex.constructor !== RegExp) {
var regex = /\{(\w+)\}/ig;
}
var m, str = this;
while((m = regex.exec(str)) !== null) {
str = str.replace(m[0], reps[m[1]]);
}
return str;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment