【问题标题】:Using jQuery, how I can get the file portion of the URL?使用 jQuery,如何获取 URL 的文件部分?
【发布时间】:2011-10-18 16:16:43
【问题描述】:

如何使用 jQuery 获取 URL 的 URL 部分?

我有这个网址:http://127.0.0.1/deposito/site/main/lojas.php。我怎样才能得到lojas.php

【问题讨论】:

    标签: javascript jquery url


    【解决方案1】:

    您可以使用 JavaScript 和正则表达式来检索文件名,如下所示:

    function GetFilename(url){
       if (url){
          var m = url.toString().match(/.*\/(.+?)\./);
          if (m && m.length > 1){
             return m[1];
          }
       }
       return "";
    }
    

    上述解决方案更全面,但在大多数情况下,这种简单的方法也适用:

    var filename = url.match(/.*\/(.+?)\./);
    

    如果需要使用jQuery,可以使用jQuery-URL-Parser插件:

    var file = $.url.attr("file");
    

    这是插件的链接:
    https://github.com/allmarkedup/jQuery-URL-Parser

    【讨论】:

      【解决方案2】:

      JavaScript:

      var pathParts = window.location.pathname.split("/");
      var file = pathParts[pathParts.length - 1];
      alert(file);
      

      【讨论】:

        【解决方案3】:

        如果是文档的当前网址,可以“split-pop”document.location.pathname:

        alert(document.location.pathname.split("/").pop());
        //-> "lojas.php"
        

        否则,如果您在字符串中包含 URL,则需要删除任何哈希或查询字符串:

        var url = "http://127.0.0.1/deposito/site/main/lojas.php"
        
        alert(url.replace(/(?:\?|#).+/, "").split("/").pop());
        //-> "lojas.php"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-24
          • 2013-06-14
          • 1970-01-01
          • 2016-03-02
          • 1970-01-01
          • 1970-01-01
          • 2020-12-04
          • 1970-01-01
          相关资源
          最近更新 更多