相对地址转绝对地址


发一个相对地址转绝对地址的函数
  <script type="text/javascript">
  <!--
mapURL=function(baseURL,href){
    if(/^http:/.test(href)){return href};
    var p1=baseURL.replace(/^http:|/?.*$|//$/g,"").split("/");
    if(p1.length>1&&//w+/./w+$/.test(p1[p1.length-1])){p1.pop()}
    if(href.charAt(0)=="/"){return "http://"+p1[0]+href};
    if(!/^/././//.test(href)){return "http://"+p1.join("/")+"/"+href};
    var p2=href.split("/");
    for(var i=0;i<p2.length;i++){
        if(p2[i]==".."&&p1.length>1) p1.pop();
        else break;
    };
    p2.splice(0,i);
    return "http://"+p1.join("/")+"/"+p2.join("/").replace(//././//g,"");
};

alert(mapURL("http://www.baidu.com/time","/g.htm"));
alert(mapURL("http://www.baidu.com/time/2008/","../g.htm"));
alert(mapURL("http://www.baidu.com/time/2008/","http://www.qq.com"));

  //-->
  </script>

javascript实现相对路径转绝对路径

今天在研究jQuery ajax功能的时候遇到一个问题,通过$.load(”url a”) Load一个网页的链接后获取到的地址信息是相对于当前运行ajax程序的网页的绝对地址。
比如我在 c:/xxxx/a.html 网页运行
$.load(”http://www.romotc.com a”).each(
function(){
alert($(this).attr(”href”));
}
);
www.romotc.com 网页中有一个链接 <a href=”/a.html”>a boby</a>
则弹出的信息为 c:/a.html
即/转换成了当前驱动器根路径
假如在www.baidu.com/xxxx/b.html运行上述ajax代码弹出的信息为http://www.baidu.com/a.html
/转换成了当前域名的根。
那么怎么才能转换成为真正的绝对地址呢?
废话少说看代码吧:


mapURL=function(baseURL,href){
if(/^http:/.test(href)){return href};
var p1=baseURL.replace(/^http:|/?.*$|//$/g,”").split(”/”);
if(p1.length>1&&//w+/./w+$/.test(p1[p1.length-1])){p1.pop()}
if(href.charAt(0)==”/”){return “http://”+p1[0]+href};
if(!/^/././//.test(href)){return “http://”+p1.join(”/”)+”/”+href};
var p2=href.split(”/”);
for(var i=0;i

if(p2[i]==”..”&&p1.length>1) p1.pop();
else break;
};
p2.splice(0,i);
return “http://”+p1.join(”/”)+”/”+p2.join(”/”).replace(//././//g,”");
};
alert(mapURL(”http://www.baidu.com/time”,”/g.htm”));
alert(mapURL(”http://www.baidu.com/time/2008/”,”../g.htm”));
alert(mapURL(”http://www.baidu.com/time/2008/”,”http://www.qq.com”));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值