zoukankan      html  css  js  c++  java
  • 一个不错的JavaScript解析浏览器路径方法

    JavaScript中有时需要用到当前的请求路径等涉及到url的情况,正常情况下我们可以使用location对象来获取我们需要的信息,本文从另外一个途径来解决这个问题,而且更加巧妙

    方法如下:

    1. function parseURL(url) {
    2. var a =  document.createElement('a');
    3. //创建一个链接
    4. a.href = url;
    5. return {
    6. source: url,
    7. protocol: a.protocol.replace(':',''),
    8. host: a.hostname,
    9. port: a.port,
    10. query: a.search,
    11. params: (function(){
    12. var ret = {},
    13. seg = a.search.replace(/^?/,'').split('&'),
    14. len = seg.length, i = 0, s;
    15. for (;i<len;i++) {
    16. if (!seg[i]) { continue; }
    17. s = seg[i].split('=');
    18. ret[s[0]] = s[1];
    19. }
    20. return ret;
    21. })(),
    22. file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
    23. hash: a.hash.replace('#',''),
    24. path: a.pathname.replace(/^([^/])/,'/$1'),
    25. relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
    26. segments: a.pathname.replace(/^//,'').split('/')
    27. };
    28. }
    复制代码


    使用方法如下:

    1. var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
    2. myURL.file;     // = 'index.html'
    3. myURL.hash;     // = 'top'
    4. myURL.host;     // = 'abc.com'
    5. myURL.query;    // = '?id=255&m=hello'
    6. myURL.params;   // = Object = { id: 255, m: hello }
    7. myURL.path;     // = '/dir/index.html'
    8. myURL.segments; // = Array = ['dir', 'index.html']
    9. myURL.port;     // = '8080'
    10. myURL.protocol; // = 'http'
    11. myURL.source;   // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
    复制代码
  • 相关阅读:
    ZOJ 3642 多重匹配 离散化.cpp
    POJ 1840 Eqs.cpp 【 Hash 】
    Hdu 4293 DP
    Hlg 1407 【最小点权覆盖】.cpp
    Hdu 3605 多重匹配
    POJ 2195 【二分图最佳匹配】.cpp
    Hdu 4292 Food.cpp 最大流+拆点
    POJ 3469 【最小割】.cpp
    limit_choices_to a value on a field in the same model Google Groups
    Django: limit_choices_to (Is this correct) Stack Overflow
  • 原文地址:https://www.cnblogs.com/mliudong/p/3619420.html
Copyright © 2011-2022 走看看