Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change ALL links, hrefs,urls with vanilla Javascript & regex

I am trying to replace the url values on the entire page using some vanilla Javascript. I cannot use ANY library/framework. Here's what I have so far which has been placed at the top of each page between the tags:

<script type="text/javascript">
function change_url() {
    var str = '';
    str = str.replace(/blog\.domain\.info/g, 'blogtest\.domain\.info');
}
change_url();
</script>

However, this isn't working when the page loads.

Basically, I need resource links to go from http://blog.domain.info to http://blogtest.domain.info. Simple task, I know! But the code above isn't working so far.

Suggestions on what to change?

like image 270
JsusSalv Avatar asked Feb 08 '11 23:02

JsusSalv


1 Answers

After reading your comment, you need something like

function replace_url(elem, attr) {
    var elems = document.getElementsByTagName(elem);
    for (var i = 0; i < elems.length; i++)
        elems[i][attr] = elems[i][attr].replace('blog.domain.info', 'blogtest.domain.info');
}

window.onload = function() {
    replace_url('a', 'href');
    replace_url('img', 'src');
    // etc
}
like image 183
Peter C Avatar answered Sep 21 '22 12:09

Peter C