Skip to content

Instantly share code, notes, and snippets.

@yoko
Created December 9, 2009 08:39
Show Gist options
  • Save yoko/252349 to your computer and use it in GitHub Desktop.
Save yoko/252349 to your computer and use it in GitHub Desktop.
String.prototype.toImageTag = function(prefix, suffix, attr) {
prefix = prefix || '';
suffix = suffix || '.png';
attr = attr ? ' '+attr : '';
var img = [];
for (var i = 0, l = this.length; i < l; i++) {
var n = this.charAt(i);
img.push(['<img src="', prefix, n, suffix, '" alt="', n, '"', attr, '/>'].join(''));
}
return img.join('');
};
Number.prototype.toImageTag = function(prefix, suffix, attr) {
return this.toString().toImageTag(prefix, suffix, attr);
};
test('String.prototype.toImageTag', function() {
var tag;
tag = 'abc'.toImageTag();
equals(tag, '<img src="a.png" alt="a"/><img src="b.png" alt="b"/><img src="c.png" alt="c"/>',
'string to html tag');
tag = '123'.toImageTag();
equals(tag, '<img src="1.png" alt="1"/><img src="2.png" alt="2"/><img src="3.png" alt="3"/>',
'number string to html tag');
tag = '123'.toImageTag('/path/to/file', '.jpg', 'class="test"');
equals(tag, '<img src="/path/to/file1.jpg" alt="1" class="test"/><img src="/path/to/file2.jpg" alt="2" class="test"/><img src="/path/to/file3.jpg" alt="3" class="test"/>',
'with options');
tag = '0'.toImageTag();
equals(tag, '<img src="0.png" alt="0"/>');
});
test('Number.prototype.toImageTag', function() {
tag = (123).toImageTag();
equals(tag, '<img src="1.png" alt="1"/><img src="2.png" alt="2"/><img src="3.png" alt="3"/>',
'number to html tag');
tag = (123).toImageTag('/path/to/file', '.jpg', 'class="test"');
equals(tag, '<img src="/path/to/file1.jpg" alt="1" class="test"/><img src="/path/to/file2.jpg" alt="2" class="test"/><img src="/path/to/file3.jpg" alt="3" class="test"/>',
'with options');
tag = (0).toImageTag();
equals(tag, '<img src="0.png" alt="0"/>');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment