2015-10-20 87 views
2

jQuery的删除基本URL如果我有像利用链接

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

的链接列表示例我怎么能在页面加载(jQuery的),在结尾处,删除网站地址,所以只具有相对URL一样

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

这个怎么样的解决方案: [转换相对路径绝对使用JavaScript(http://stackoverflow.com/questions/14780350 /转换相对路径绝对使用JavaScript) – AlexBerd

回答

1

还有就是代码段共享,除去基本的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; 
} 

你可以用callbac使用.attr()方法的k个功能:

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

Working Demo

+1

[String.prototype.replace](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/替换)也接受一个正则表达式作为第一个参数,所以你可以使用'url.replace(baseUrlPattern,“”)''。它可能更具可读性? –

+0

这对于像https://hello-there.test.com/match这样的URL不起作用(它返回“-there.test.com/match”) – Willster

0

请各位看看下面的代码片段。为了演示目的,我使用了href,从http://stacksnippets.net/开始。希望它能帮助你一点。

首先点击“打印Href”按钮查看原始href。然后点击“从Href删除基地”按钮,该按钮将更改href以从所有<a>标签中删除网站地址。然后点击“打印HREF”按钮,再点击查看修订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>