Created
March 5, 2013 04:11
-
-
Save Cosmicist/5087928 to your computer and use it in GitHub Desktop.
Simple JavaScript string formatter with possibility for custom regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>String format</title> | |
</head> | |
<body> | |
<h2>Default</h2> | |
<p> | |
<pre>Replacing <strong>{foo}</strong> and <strong>{bar}</strong></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 <strong>:foo</strong> and <strong>:bar</strong></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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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