...

View Full Version : search and replace



NancyJ
04-28-2006, 10:51 AM
I'm building a new site that takes data from external sources, but we dont want large load times so I'm using XMLhttpRequest objects to get the data after the page is loaded, which is all fine but I dont want to create 2 versions of the site, so I wondered if it was possible to search for specific text in the page and replace it - ie look for the links to the no-script versioned pages and replace them with links to the 'hi tech' version.

Kor
04-28-2006, 11:09 AM
Not very clear to me... First you say text than you say link. From the nodeType point of view, it is not the same thing.

Now, yes, you may find/refere/replace everything on the page, using various DOM methods, but you must be more specific.

NancyJ
04-28-2006, 11:19 AM
ok I want to replace links to accom.php to accomx.php

Kor
04-28-2006, 12:03 PM
this should work, if I well understood what you want to replace:



<script type="text/javascript">
onload = function(){
var aa=document.getElementsByTagName('a');
for(var i=0;i<aa.length;i++){
aa[i].href&&aa[i].href.match(/accom.php/)?aa[i].href=aa[i].href.replace(/accom.php/g,'accomx.php'):null;
}
}
</script>

NancyJ
04-29-2006, 08:09 AM
this should work, if I well understood what you want to replace:



<script type="text/javascript">
onload = function(){
var aa=document.getElementsByTagName('a');
for(var i=0;i<aa.length;i++){
aa[i].href&&aa[i].href.match(/accom.php/)?aa[i].href=aa[i].href.replace(/accom.php/g,'accomx.php'):null;
}
}
</script>

OK, just because I like to know what stuff does before I paste it in ;) Mind telling me if this interpretation is correction

onload = function(){
//I'm assuming that this is instead of <body onload="function()" - is this a new thing, I dont keep up to date with javascript but if this works cross browser, it seems strange to me that people havent been doing it for years...

var aa=document.getElementsByTagName('a');
// local variable aa = array of link elements
for(var i=0;i<aa.length;i++){
//for each link element
aa[i].href&&aa[i].href.match(/accom.php/)?aa[i].href=aa[i].href.replace(/accom.php/g,'accomx.php'):null;
//if the link element has an href and the href = accom.php then change the href to accomx.php, otherwise leave it alone.
}
}
[/code]
Is that right? Not sure about the replace, why doesnt the first term have quotes around it and why does it end in /g?

Kor
04-29-2006, 08:32 AM
Correct. Now about the replace... I have used RegularExpression

string.match(/substring/)
tries to find if the substring is anywere inside the string. If so:

string = string.replace(/substring/g,'anothersubstring')
replaces the subtring whereever it might be (g is a RegExp flag and matches global)

The /.../ container makes the expresion to be a Regular Expression. It is a shortcut for

new RegExp('substring')

object

NancyJ
04-29-2006, 08:33 AM
cheers :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum