js相对路径转绝对路径方法abs-url

2017-11-07 | 5,606浏览 | 0评论 | 标签:abs-url 相对路径

js相对路径转绝对路径方法

最近在尝试爬一个网站,网站图片使用了相对和绝对两种路径,导致某些图片下载失败。先百度一下牛人的解决方法,加以修改,现在基本能满足自己项目要求。

网上的方法:

<script>
function canonical_uri(src, base_path) {
  var root_page = /^[^?#]*\//.exec(location.href)[0],
    root_domain = /^\w+\:\/\/\/?[^\/]+/.exec(root_page)[0],
    absolute_regex = /^\w+\:\/\//;
  if (/^\/\/\/?/.test(src)) {
    src = location.protocol + src;
  } else if (!absolute_regex.test(src) && src.charAt(0) != "/") {
    src = (base_path || "") + src;
  }
  return absolute_regex.test(src) ? src : ((src.charAt(0) == "/" ? root_domain : root_page) + src);
}

//test
document.write(canonical_uri('1.jpg')+'<br/>');
document.write(canonical_uri('/1.jpg')+'<br/>');
document.write(canonical_uri('./1.jpg')+'<br/>');
document.write(canonical_uri('../1.jpg')+'<br/>');
</script>

因为自己使用node, 没有location对象,且上面的代码不能解析../相对路径,以下是自己优化后的版本:

增强版:

  • 1.纯js,不需要jQuery;
  • 2.纯字符串匹配,不依赖window.location,可用于node环境;
  • 3.支持import和require;
  • 4.支持npm模块加载: $ npm install abs-url;
  • 5.兼容了几种常用的路径转化情况,demo中有示例

(函数排版比较随意,请自行美化)

<script>
/**
 * absUrl.js 相对路径->绝对路径函数
 * DH (http://denghao.me)
 * 2017-11-08 09:48:52
 */
;
(function() {
  function MyModule(src, basePath) {
    var protocol = /^((ht|f)tps?)/.exec(basePath),
      basePath = protocol ? basePath : 'http://' + basePath,
      domain = /^\w+\:\/\/\/?[^\/]+/.exec(basePath)[0];

    function deleteLastFolder(str) {
      var i = str.lastIndexOf("\/");
      if (i < 10) {
        return str;
      } else {
        return str.substring(0, i);
      }
    }

    function folderParse(path) {
      var level = 0,
        name = path.replace(/\.\.\//g, function(v) {
          level++;
          return '';
        });
      return {
        level: level,
        name: name
      }
    }

    function basePathParse(path, basePath) {
      var folder = folderParse(path);
      basePath = basePath.replace(/(.*)\/+$/g, '$1');
      for (var i = 0; i < folder.level; i++) {
        basePath = deleteLastFolder(basePath)
      }
      return basePath + '/' + folder.name;
    }

    if (/^\/\/\/?/.test(src)) {
      // eg.  //cdn.com/1.jpg
      src = (protocol ? (protocol[0] + ':') : 'http:') + src;
    } else if (!/^\w+\:\/\//.test(src)) {
      if (/^\/+/.test(src)) {
        // eg.  /1.jpg
        src = domain + src;
      } else if (/^\.\/+/.test(src)) {
        // eg.  ./1.jpg
        src = src.replace(/^\.\/+/, '');
        src = basePath + '/' + src;
      } else if (/^\.\.\/+/.test(src)) {
        // eg.  ../1.jpg
        src = basePathParse(src, basePath)
      } else {
        // eg.  1.jpg
        src = basePath + '/' + src;
      }
    }
    return src;
  }

  var absUrl = MyModule;
  if (typeof module !== 'undefined' && typeof exports === 'object') {
    module.exports = absUrl;
  } else if (typeof define === 'function' && (define.amd || define.cmd)) {
    define(function() {
      return absUrl;
    });
  } else {
    this.absUrl = absUrl;
  }
}).call(this || (typeof window !== 'undefined' ? window : global));

// test
document.write(absUrl('1.jpg', 'http://denghao.me/a')+'<br/>');
document.write(absUrl('/1.jpg', 'http://denghao.me/a')+'<br/>');
document.write(absUrl('./1.jpg', 'http://denghao.me/a')+'<br/>');
document.write(absUrl('../1.jpg', 'http://denghao.me/a')+'<br/>');

//更变态的
document.write(absUrl('1.jpg', 'denghao.me')+'<br/>');
document.write(absUrl('//cdn.bootcss.com/1.jpg', 'http://denghao.me')+'<br/>');
document.write(absUrl('http://cdn.bootcss.com/1.jpg', 'http://denghao.me')+'<br/>');
document.write(absUrl('../../../../../../../1.jpg', 'http://denghao.me/a')+'<br/>');
</script>

使用方法:

上面的demo写得很清楚了,直接调用absUrl()方法。如果你项目使用npm,也可以直接npm install abs-url安装调用。

源码已放在gitHub: https://github.com/denghao123/abs-url


ps:node中的url模块也提供类似方法, 链接在此[[url module]][3]。

(本篇完。有疑问欢迎留言探讨)

留言:

*

* (方便回复通知)

打赏
编辑代码 运行结果
退出