PDA

View Full Version : Replacing words with HTML



MarkDarkness
02-28-2009, 06:48 AM
Hello, all.

I'm in need of a script that's able to replace occurrences of specific words in the document's body with some HTML. It's easy to do that with "str.replace", but that method relies on the script also generating the text, which will definitely not work for my project. I've seen a lot of scripts that replace words with different words, but none that supports HTML.

Just to be clear, an example: "There are a lot of houses in that area."
Intended result: "There are a lot of <img src="house.png"> in that area."

Lame example, but that's the idea.

Hope somebody can help me out on this one... thank you for the attention.

Nile
03-01-2009, 01:11 AM
You can't do it in HTML... You can do it in PHP though:
http://www.dynamicdrive.com/forums/showpost.php?p=183191&postcount=2

MarkDarkness
03-02-2009, 02:15 AM
My problem is that this project is completely client-side. Are there really no alternatives? Combining some manner of find & replace code with "document.write" should do it, I think... I just don't know how to implement that.

Falkon303
03-02-2009, 03:52 AM
when in doubt, use dynamic posting/ajax.

MarkDarkness
03-02-2009, 03:59 AM
Well, as I was saying, this project is client-side... I don't have a server to interact with. The whole thing is supposed to run from a pendrive. With creativity I've circumvented a lot of limitations, but this one's a tough cookie.

Anyway, that's why AJAX is out of question, unfortunately.

Medyman
03-02-2009, 04:01 AM
This (http://patrickhaney.com/thinktank/2008/08/19/automatic-awesompersands) is an article by Patrick Haney about ampersands and typography. In it, he discusses a way to wrap ampersands in <span> tags to be able to style them differently. You can use the same principle (and practically the same code) to do what you're looking for.

MarkDarkness
03-02-2009, 05:21 AM
That was one fine suggestion, Medyman! Works like a charm. Thank you very much for the help, it's very appreciated.

One last question, though... to those of you more familiar with jQuery... is there any way I could turn the code below into some some sort of array? So that I don't have to repeat it over and over again to add different replacements?


$(document).ready(function() {
$("*:contains('WORD GOES HERE')", document.body)
.contents()
.each(
function() {
if( this.nodeType == 3 ) {
$(this)
.replaceWith( this
.nodeValue
.replace( /WORD GOES HERE/g, "<img src='images/layout/house.png' alt='house icon'>" )
);
}
}
);
});

Falkon303
03-02-2009, 06:46 PM
I am curious if the

document.getElementById('fielder').value.replace(new RegExp(/\,/g),"-");

regex function would insert html.....

probably not, but that would be so much more convenient.