I am trying to write a script that, after the page load, will replace all my existing links with links in a different format.
However, while I've managed to work out how to do the link string manipulation, I'm stuck on how to actually replace it on the page.
I have the following code which gets all the links from the page, and then loops through them doing a regular expression to see if they match my pattern and then if they do taking out the name information from the link and creating the new link structure - this bit all works. It's the next stage of doing the replace where I'm stuck.
var str;
var fn;
var ln;
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
str = links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi);
if (links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi)) {
var linkSplit = links[i].href.split("/");
// Get the last one (so the .aspx and then split again).
// Now split again on the .
var fileNameSplit = linkSplit[linkSplit.length-1].split(".");
var nameSplit = fileNameSplit[0].split(/(?=[A-Z])/);
fn = nameSplit[0];
ln = nameSplit[1];
if(nameSplit[2]){
ln += nameSplit[2];
}
// Build replacement string
var replacementUrl = 'https://www.testsite.co.uk/services/people.aspx?fn='+fn+'&sn='+ln;
// Do the actual replacement
links[i].href.replace(links[i].href, replacementUrl);
}
I've tried a couple of different solutions to make it do the actual replacement, .replace, .replaceWith, and I've tried using a split/join to replace a string with an array that I found here - Using split/join to replace a string with an array
var html = document.getElementsByTagName('html')[0];
var block = html.innerHTML;
var replace_str = links[i].href;
var replace_with = replacementUrl;
var rep_block = block.split(replace_str).join(replace_with);
I've read these, but had no success applying the same logic:
How can I fix this problem?
replacedoesn't modify the string you apply it to, rather it returns a new string with the replacement in it. You would then still need to assign it to.hrefin the same manner.