function makeLinks(context, url) {
var sets = context ? $(context + ' a') : $('a'),
prot = url || window.location.protocol;
if(prot.match(/https/)){
lockup(sets);
}
function lockup(elem) {
elem.each(function(){
var self = $(this),
href = self.attr('href');
if(href.match(/http[^s]/)){
// This logs the correct output
console.log(href.replace('http','https'));
// This fails
href.replace('http','https');
}
});
}
}
The purpose of the function is to check the current protocol of the window object.
If it is ‘https:’, then I want the anchors that have a href of ‘http’ to be ‘https’.
The function is called like this: makeLinks(‘#wrapper’, ‘https:’);
The second parameter is just for testing, otherwise it would use window.location.protocol
Currently, when I call this function on markup that looks like this:
<a href="http://cross-origin-denial.com"></a>
<a href="http://pleasesecureme.com"></a>
<a href="https://imcool.com"></a>
<div id="wrapper">
<a href="http://cross-origin-denial.com"></a>
<a href="http://imscrewed.com"></a>
<a href="http://yougotmetoo.com"></a>
<a href="https://imcool.com"></a>
</div>
The console logs exactly what I want to happen, however, the actual href remains unchanged inside of the DOM.
I’ve tested this out in Chrome and Firefox with the same result
I’m pretty sure that my logic is wrong somewhere (or everywhere)
If someone can help me understand why, I would be very appreciative 🙂
You’re not doing anything with the result of the
.replace().You need to set the new value.
or a nicer way is like this: