Hope someone can explain some weird behavior I came across with jQuery. The following script searches for relative links on my page and replaces them with absolute links.
$(document).ready(function() { $("a[href^='/']").each(function(){ var cur_href = $(this).prop("href"); $(this).prop("href", 'http://www.mysite.com'+cur_href); }); });
I use this script on a page that will be transmitted over https, but I do not want all of my navigation to link to https pages. Since my navigation system was included globally, this seemed like the easiest way to fix the problem.
The problem that I am facing comes in a real replacement. The second line of the script matches all the relative links on the page correctly and then runs the replaceable part of the script. It is in replacement, line 4, where I get some strange results. After this part of running the script, my URLs look like this:
Http: //www.mysite.comhttps//www.mysite.com/mypage.htm
Obviously, I am not doing what I want. It seems that the first part of the script corresponds to the relative URL, but when the spare part fires, the browser is already tied to the domain information.
The only thing I have found so far that actually does what I want is to write a replacement, expecting the browser to overlay:
this.href = this.href.replace(/^https:\/\/www\.mysite\.com\//, "http://www.mysite.com/");
Is there a better way to do this?
Edit: here is the jsfiddle problem .
source share