How do I replace a character contained within a DIV, and replace with a image, using Jquery?
I was wondering if there is a way of replacing plain text in a div.number-plate
, with a image for every character(on开发者_JAVA百科e by one)? I am using JQuery
Any help is greatly appreciated, Thanks
Since @AndyE laid down the code golf gauntlet here, you can use a regex to replace all the chacters with images, like this:
$("div.number-plate").html(function(i, h) {
return h.replace(/(.)/g, '<img src="images/char-$1.gif" />');
});
You can test it out here.
Also, it seems you didn't want a ransom note generator, but I did! so here it is. Sample result:
http://www.joshuarey.com/ransom/w/2.gifhttp://www.joshuarey.com/ransom/e/3.gif
(source: joshuarey.com)
http://www.joshuarey.com/ransom/a/13.gifhttp://www.joshuarey.com/ransom/v/5.gif
(source: joshuarey.com)
(source: joshuarey.com)
(source: joshuarey.com)
(source: joshuarey.com)
http://www.joshuarey.com/ransom/r/3.gif http://www.joshuarey.com/ransom/d/4.gif
(source: joshuarey.com)
http://www.joshuarey.com/ransom/g/2.gif
var div = $("div.number-plate"),
txt = div.text(),
pre = '<img src="images/char-',
suf = '.gif">',
result = pre + txt.split("").join(suf+pre) + suf;
div.html(result);
Sample number plate:
V332LAE
Sample result:
It's a short, simple solution in which you would also need images for punctuation characters if they exist in your text. Since you're working with number plates, that shouldn't be an issue.
Thanks to @Nick for introducing me to http://dummyimage.com, I've set up a demo of my own:
http://www.jsfiddle.net/aCdLR/
var charMap = {
'A': 'A.gif', 'B': 'B.gif' // ... etc.
}
$("div.number-plate").each(function() {
var text = $(this).text(); // Assuming no HTML content
var out = [];
for (var i = 0, len = text.length; i < len; i++) {
var img= charMap[text.charAt(i)];
if (img) out.push("<img src='" + img + "'>");
}
$(this).html(out.join(""));
});
(untested)
Something like this:
$(document).ready(function() {
var str = $('div.number-plate').html();
var output = '';
for (i = 0; i < str.length; i++) {
var char = str.substr(i, 1);
output = output + '<img src="/images/characters/' + char + '.gif" />';
}
$('div.number-plate').html(output);
});
If you need to transform each character (or filter out non-alnums) the $.map()
could be used:
$('.number-plate').html(function(i, o) {
var imgs = $.map(o.split(''), function(c) {
return '<img src="images/' + c.toLowerCase() + '.png" />';
});
return imgs.join('');
});
Characters can be filtered out by returning NULL
in the mapping function.
(Demo - with dummy images (no reason to use $.map()
, though))
精彩评论