【问题标题】:Replace parts of a URL in Greasemonkey在 Greasemonkey 中替换部分 URL
【发布时间】:2014-09-19 00:15:45
【问题描述】:

我正在尝试使用 Greasemonkey 脚本替换部分 url,但很难实现我想要做的事情。

原始网址如下:

http://x1.example.to/images/thumb/50/157/1571552600.jpg
http://x2.example.to/images/thumb/50/120/1201859695.jpg
http://x3.example.to/images/thumb/50/210/2109983330.jpg

我想要实现的是:

http://example.to/images/full/50/157/1571552600.jpg
http://example.to/images/full/50/120/1201859695.jpg
http://example.to/images/full/50/210/2109983330.jpg

我只想将 thumb 替换为 full 并删除 x1.example.to, x2 .example.to、x3.example.to、x4.example.to 等完全来自原始 URL,因此新的 URL 将以 example.to/images/full/

我如何做到这一点?

我从this answer 找到了一个 Greasemonkey 脚本,并尝试解决但失败了。

这是我到目前为止所做的。

// ==UserScript==
// @name           Example Images Fixer
// @namespace      Example
// @description    Fixes image galleries
// @include        http://*.example.to/*
// ==/UserScript==

var links = document.getElementsByTagName("a"); //array
var regex = /^(http:\/\/)([^\.]+)(\.example\.to\/images\/thumb/\)(.+)$/i;
for (var i=0,imax=links.length; i<imax; i++) {
   links[i].href = links[i].href.replace(regex,"$4full/$5");
}

有什么帮助吗?

【问题讨论】:

    标签: regex greasemonkey


    【解决方案1】:

    您忘记将http:// 部分放在替换网址中:

    /^(https?:\/\/)[^.]+\.(example\.to\/images\/)thumb\/(.+)$/i
    

    然后:

    .replace(regex, "$1$2full/$3");
    

    你可以看到结果here

    【讨论】:

      【解决方案2】:

      这是一个可以做的例子:

      var urls = ['http://x1.example.to/images/thumb/50/157/1571552600.jpg',
      'http://x2.example.to/images/thumb/50/120/1201859695.jpg',
      'http://x3.example.to/images/thumb/50/210/2109983330.jpg'];
      
      
      for (var i = 0, len = urls.length; i < len; i++) {
      
          urls[i] = 
            urls[i].replace(/:\/\/[^\.]+\.(example.to\/images\/)thumb/, '://$1full');
          console.log(urls[i]);
      
      }
      
      /* result
      "http://example.to/images/full/50/157/1571552600.jpg"
      "http://example.to/images/full/50/120/1201859695.jpg"
      "http://example.to/images/full/50/210/2109983330.jpg"
      */
      

      这里是Fiddle

      【讨论】:

        猜你喜欢
        • 2017-01-15
        • 1970-01-01
        • 1970-01-01
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-29
        相关资源
        最近更新 更多