2

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>
1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

String.prototype.replace also accepts a regex as the first parameter, so you could use url.replace(baseUrlPattern, ""). It might be more readable?
this doesn't work for URLs such as hello-there.test.com/match (it returns "-there.test.com/match")
A better regex for this would be /^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i
0

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>

  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.