代码之家  ›  专栏  ›  技术社区  ›  Thomas

正则表达式:如何通过正则表达式和jQuery捕获url的第二部分

  •  1
  • Thomas  · 技术社区  · 8 年前

    这是我的url,我需要分成两部分。

    1) http://localhost:8800/gb/
    
    2) http://localhost:8800/gb/About.aspx
    
    3) http://localhost:8800/gb/product.aspx?id=1&vref=201
    
    4) http://localhost:8800/gb/Contact.aspx
    

    现在告诉我应该使用哪个正则表达式来拆分上述url。 第二部分将保存来自国家代码后的url

    假设这是我的url http://localhost:8800/gb/About.aspx 所以第二部分是关于。aspx公司

    我有一个正则表达式 (https?:\/\/[^\/]+)\/(.*) 这将url分为两部分,但我想从国家代码中获取。谢谢

    2 回复  |  直到 8 年前
        1
  •  2
  •   Marco    8 年前

    一种可能的方法是 ^(?:\/\/|[^\/]+)*\/[a-zA-Z]{2}\/ . 这只是基于 Get relative URL from absolute URL 添加了2个字符的国家代码。

    演示: https://regex101.com/r/5fpRWX/1/

        2
  •  1
  •   anubhava    8 年前

    您可以使用 split 关于带有 / 在任何一侧:

    var url = 'http://localhost:8800/gb/About.aspx?id=2&vref=3';
    var arr = url.split(/\/[a-z]{2}\//);
    
    console.log(arr[0]); //=> http://localhost:8800
    console.log(arr[1]); //=> About.aspx?id=2&vref=3

    RegEx Demo