Link Replacement With JavaScript [closed]

If you’re trying to change the src of the <img> tag(which is what I’m supposing, reading the question) then you need to do something like this:

function changeSrc() {
    var img = document.getElementsByTagName('img')[0];
    img.src = img.src.replace('cdn/backup/', 'newcdn/folder/');

window.onload = changeSrc;

From the comments I read that you want to change ALL the srcs, so the code will look like this:

function changeAllSrcs() {
    var imgs = document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; i++) {
        var img = imgs[i];
        img.src = img.src.replace('cdn/backup/', 'newcdn/folder/');

window.onload = changeAllSrcs;

I don’t know if this is a good way to do this, but if you want to replace all the occurences with link then you should do something like this(I don’t like this solution, and it is not totally safe too, anyway it should do the job):

function replaceLinks() {
    var bodyHtml = document.body.innerHTML,
        replaced = bodyHtml.replace(/cdn\/backup/g, 'newcdn/folder/');
    document.body.innerHTML = replaced;
window.onload = replaceLinks;

Browse More Popular Posts

Leave a Comment