【问题标题】:Change URL with wildcard使用通配符更改 URL
【发布时间】:2018-05-22 09:11:53
【问题描述】:

我不知道标题是否合适(抱歉)。 首先,我必须告诉你,我是 javascript 的新手。

我想制作更改 URL 的 javascirpt 并在单击时重定向它(在书签栏上创建)。 这个想法是改变URL:

https://mail.google.com/mail/u/0/h/[12_random_aphanumeric]/?&th=[16_random_aphanumeric]&v=c&s=a

https://mail.google.com/mail/u/0/#all/[16_random_aphanumeric]

例如更改:

https://mail.google.com/mail/u/0/h/bv293r3qycgk/?&th=16032287bb796882&v=c&s=a

https://mail.google.com/mail/u/0/#all/16032287bb796882


所以我像这样使用“window.location.assign”:

javascript: window.location.assign(window.location.toString().replace('*?&th=', 'https://mail.google.com/mail/u/0/#all/')); window.location.assign(window.location.toString().replace('&v=c&s=a', ' '));

当然它不起作用。

我只是不知道如何在上面使用 [*] 通配符。

任何建议都将不胜感激。

【问题讨论】:

    标签: javascript html url url-rewriting friendly-url


    【解决方案1】:

    .replace 不支持“通配符”之类的东西。您要查找的内容称为regular expression。正则表达式中的* 称为Kleene closure

    gmailUrlRegex = /(https:\/\/mail\.google\.com\/mail\/u\/0)\/h\/[A-z0-9]{12}\/\?&th=([A-z0-9]{16}).*/;
    location.href = location.href.replace(gmailUrlRegex, "$1/#all/$2");
    

    可视化正则表达式:https://www.debuggex.com/r/eAkLwrgNQcuUCisN

    var input = "https://mail.google.com/mail/u/0/h/bv293r3qycgk/?&th=16032287bb796882&v=c&s=a";
    console.log(input.replace(/(https:\/\/mail\.google\.com\/mail\/u\/0)\/h\/[A-z0-9]{12}\/\?&th=([A-z0-9]{16}).*/, "$1/#all/$2"));

    【讨论】:

      【解决方案2】:

      捕获th 参数并连接到新路径

      var str='https://mail.google.com/mail/u/0/h/1a2b3c4d5e6f/?&th=abcd1234abcd1234&v=c&s=a',
       th = str.match(/(th=[a-z0-9]{16})/i)[0],
       url = 'https://mail.google.com/mail/u/0/#all/' + th;
      
      console.log(url)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多