【问题标题】:Use regex to match URL up to the last forward slash使用正则表达式将 URL 匹配到最后一个正斜杠
【发布时间】:2020-04-27 18:59:00
【问题描述】:

尝试从以下位置提取值:

<img src="https://www.google.com/one/two/three/file.png"/>"https://www.google.com/one/file.jpg"

到:

"https://www.google.com/one/two/three/" "https://www.google.com/one/"

我基本上想将基本 url 中的所有内容捕获到最后一个正斜杠。

我尝试使用/https://([-a-zA-Z0-9()@:%_\+.~#?&amp;//=]*)?/ 捕获整个网址,但我不知道如何在 html 文件中网址的最后一个“/”处停止匹配

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    试试 split split() 方法,这会让你的问题更简单

    function str(str_url){
     var arr = str_url.split('/');   //splits url at every '/'
     arr.pop();    //this pops the last term in url
     str_url = arr.join('/');    //finally joins everything 
     return str_url;
    }
    

    MDN web docs了解更多信息

    【讨论】:

      【解决方案2】:

      如果您确定格式,您可以使用:

      https?:\/\/[^/"]+([^/"]+\/)+
      

      在哪里

      • https?:\/\/[^/"]+ 匹配 https:// 以及直到第一个 /
      • ([^/"]+\/)+ 匹配abc/ 的一个或多个实例

      另请参阅:https://regex101.com/r/6ohuWP/1

      【讨论】:

        猜你喜欢
        • 2013-05-15
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-26
        相关资源
        最近更新 更多