Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing a string in an HTML page using JavaScript

Status
Not open for further replies.

Firebrandbooma

Programmer
Sep 4, 2007
5
0
0
GB
Hello everyone,

Can anyone help me with replacing multiple occurances of a string in an HTML page.

I know how to replace a string like this:

<script language="javascript">
var str1, str2;
str1 = "Scripting JavaScript";
str2 = str1.replace ("JavaScript", "Master");
document.write ("String after replacement: " + str2);
</script>

What I need to know is how to implement this into a page(s) so that it replaces occurances within the <body> tag.

Many thanks :)
 
This code gets the body of the document and replaces all div tags with p tags using a regular expression. It then sets the body of the document back.
Code:
...
var l_pBody = document.getElementByTagName('BODY');
var l_sBody = l_pBody[0].innerHTML;
l_pBody.innerHTML = l_sBody.replace(/div>/g, "p>");
...
It's not perfect, because you could have a classname in your div (in which case the regular expression won't match it). It also invalidates any event listeners etc - but the concept is there.

Is this useful to you?

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
That is usefull, thank you.

Although I'm trying to replace a text string throughout an old site that I've inherited. The string in question could be within any number of tags with either class or ID attributes. (It's a mess and I'm looking for a quick qay round whilst I rebuild)

I've been trying this:

window.onload=function(){
var searchTerm='Microsoft';
var NewTerm='PHP';
var contents=document.body.innerHTML;
var idx=contents.search(searchTerm);
if(idx) {
contents=contents.replace(searchTerm, NewTerm);
document.body.innerHTML=contents;
}
};

but without much luck. It only works occasionaly and even then only picks up the first instance.

Cheers :)
 
Thanks. In the mean time I found this and it works:

<script type="text/javascript">
var words={
'Bill':'William','Miss':'Mrs'
}
var regs=[];
for(arg in words){regs[regs.length]=new RegExp(arg,'g')}

window.onload=function replaceText(){
var tags=document.getElementsByTagName('body')[0].getElementsByTagName('*');
var i=0,t;
while(t=tags[i++]){
if(t.childNodes[0]){
var j=0, c;
while(c=t.childNodes[j++]){
if(c.nodeType==3){
var k=0;
for(arg in words){
c.nodeValue=c.nodeValue.replace(regs[k],words[arg]);
k++;
}
}
}
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top