Thanks in advance for the help.
I have been fooling around with browser extensions (a novice) and I have been trying to figure out some word swapping issues; specifically, I am trying to do something akin to a rebus.
I tested my code out on just a plain text page, and it works. But then, when making it an extension, it basically loses the styling on the page and turns it into text only.
I have been looking for a more unobtrusive way to swap a word like “shoe” with an image of a shoe. I have been working in jQuery and using the documentation to make what I already did below.
$(document).ready(function () {
var newText = $("body").text().split(" ");
$.each(newText, function(index, value) {
if (newText[index] === "shoe") {
newText[index] = "<img src='http://.../shoe.png' alt='shoe'>";
}
});
var altText = newText.join("</span> <span>");
$("body").html(altText);
});
I see what I am doing: ripping the text out and then shoving back in. But I am at a loss of what I should use.
I am aware of the replaceWith() function and I suppose that is the right one to use. But how do I get to the “shoe” words in the first place?
Thanks
I don’t know if jQuery helps a lot here. You are best off probably just doing a replace on the full html… with some (potentially bad) notes and caveats.
1) Ideally, you would only use
text()via jQuery, but after you have the text, you have no easy way of putting it back.this is <span>my</span> dog=>this is my <img src="dog.jpg">.. losing your span.2) Replacing on the full html would be bad if your html tags contain the words you are replacing!!
<div id="dog">=><div id="<img src="dog.jpg">">Ugh!3) Use word boundary delimiters
\bshoe\bin your regular expression to match on whole words only to prevent:catastrophe=><img src="cat.jpg">astropheExample:
http://jsfiddle.net/jtbowden/7cajW/
BETTER:
I coded a better solution, using lower-level code based on
jquery.highlight.http://jsfiddle.net/jtbowden/jRebk/3/
It adds a function prototype for
.rebus(wordMap, [caseSensitive], [useWordBoundaries]), where the defaults are false and true, respectively, for the latter two.Usage: