Change head <link href=""> to another DIRECTORY by jquery/javascript

725 Views Asked by At

I want to change the head link href="..." for all my css files to target another directory by jquery/javascript, as the following:

It's currently like this:

<link href="css/style.css">

I want to change it to be like this:

<link href="../css/style.css">

My try is:

$(document).load(function () {
function headLinksChange() {
    $('head link').each(function () {
        var newurl = $(this).attr('href').replace("css", "\.\.\/css");
        $(this).attr('href', newurl);
    });
}
headLinksChange();
});

How can I do that?

Thanks

2

There are 2 best solutions below

0
Amit Joki On

You can do it this way by using the function overload of attr method of jQuery object. No need of regex, just string concatenation. There is no need of a function here, I suppose.

$('head link').attr('href', function(_, src){
    return "../" + src;
});
0
vks On
var re = /(?=css\/)/gm;
var str = '<link href="css/style.css">\n';
var subst = '../';

var result = str.replace(re, subst);