Search code examples
javascriptjqueryreplacehyperlinkhref

Replace extension from certain links


i have an array, which includes some pages:

var pages = ['test', 'blabla', 'xyz'];

My document contains some links like these:

<a href="test.php">tes</a>
<a href="blabla.php">blabla</a>
<a href="xyz.php">xyz</a>
<a href="stackoverflow.php">test2</a>

What i want is the following:

I want to search the whole document and find all links, that are starting with the words in my array. Then, i want to replace ".php" with ".html" and prepend the current URL (without the file) to them:

location.href.substring(0,location.href.lastIndexOf('/')+1)

So, the expected result should look like this:

<a href="file:///C:/test.html">test</a>
<a href="file:///C:/blabla.html">blabla</a>
<a href="file:///C:/xyz.html">xyz</a>
<a href="stackoverflow.php">xyz</a>

What i tried is this:

$(function(){
var pages = ['test', 'blabla', 'xyz'];
$.each(pages, function(index, value) {
$("a[href='" + value + ".php']").attr("href", location.href.substring(0,location.href.lastIndexOf('/')+1) + $("a[href='" + value + ".php']").attr("href").replace('php', 'html'));
});
});

This works, but not always. I tried this in a bigger document and it ends with this error:

$("a[href='" + value + ".php']").attr("href") is undefined

I guess, there's an easier, better and more compatible way. But i have no clue, that's why i ask here :D


Solution

  • var pages = ['test', 'blabla', 'xyz'];
    $.each(pages, function (index, value) {
        $('a[href$=' + value + '.php]').attr("href", function () {
            return ('file:///C:/' + $(this).attr('href').replace('.php', '.html'));
        });
    });