user1765862
user1765862

Reputation: 14145

using jquery remove base url from links

If I have for example list of links like

<a href="http://www.mywebsite.com/Scripts/xx.pdf>link1</a>
<a href="http://www.mywebsite.com/Scripts/xx1.pdf>link2</a>

how can I on page load (jquery) remove website address so at the end to have only relative url like

<a href="/Scripts/xx.pdf>link1</a>
<a href="/Scripts/xx1.pdf>link2</a>

Upvotes: 2

Views: 4103

Answers (2)

vijayP
vijayP

Reputation: 11502

Please have a look at below code snippet. For demo purpose i have used href starting with http://stacksnippets.net/. Hope it will help you a bit.

First click on "Print Href" button to see original href. Then click on "Remove base from Href" button which will change the href to remove website address from all <a> tag. Then again click on "Print Href" button to see revised href

$(document).ready(function(){
  $("#printHref").click(function(){
    $("#link1href").text($($("a")[0]).attr("href"));
    $("#link2href").text($($("a")[1]).attr("href"));
  });

   $("#changeHref").click(function(){
    $("a").each(function(){
      var websiteName = window.location.host;
      var partToReplcae = "http://"+websiteName;
      $(this).attr("href",$(this).attr("href").replace(partToReplcae,""));
    });  
  });
  
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="http://stacksnippets.net/Scripts/xx.pdf">link1</a>
<a href="http://stacksnippets.net/Scripts/xx1.pdf">link2</a>
<br/><br/>
<button id="printHref" >Print Href</button><button id="changeHref" >Remove base from Href</button>
<br/>
Link1 Href:<p id="link1href"></p>
Link2 Href:<p id="link2href"></p>

  

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

There is snippet shared to remove base url here:

function RemoveBaseUrl(url) {
/*
 * Replace base URL in given string, if it exists, and return the result.
 *
 * e.g. "http://localhost:8000/api/v1/blah/" becomes "/api/v1/blah/"
 *      "/api/v1/blah/" stays "/api/v1/blah/"
 */
var baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/;
var result = "";

var match = baseUrlPattern.exec(url);
if (match != null) {
    result = match[0];
}

if (result.length > 0) {
    url = url.replace(result, "");
}

return url;
}

You can use it with callback function of .attr() method:

$('a').attr('href',function(i,o){
  return RemoveBaseUrl(o) ;
});

Working Demo

Upvotes: 1

Related Questions