JavaScript将相对地址转换为绝对地址

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:04   1308   0
在看LABjs源代码时,发现里面有个将相对地址转为绝对地址的函数,将其拿出纪录如下:

function canonical_uri(src, base_path)
{
 var root_page = /^[^?#]*\//.exec(location.href)[0],
  root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
  absolute_regex = /^\w+\:\/\//;
 
 // is `src` is protocol-relative (begins with // or ///), prepend protocol
 if (/^\/\/\/?/.test(src))
 {
  src = location.protocol + src;
 }
 // is `src` page-relative? (not an absolute URL, and not a domain-relative path, beginning with /)
 else if (!absolute_regex.test(src) && src.charAt(0) != "/")
 {
  // prepend `base_path`, if any
  src = (base_path || "") + src;
 }

 // make sure to return `src` as absolute
 return absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src);
}


如当前页面地址为:http://www.inspurstb.com/hzt/index.html

则canonical_uri("scy.js")返回http://www.inspurstb.com/hzt/scy.js

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP