【问题标题】:Geting a file name without the ".jpg" part获取没有“.jpeg”部分的文件名
【发布时间】:2013-11-14 16:16:20
【问题描述】:

好的,我正在使用 slimbox2,并希望用户能够保存图像的高分辨率版本。 将此添加到 .js 文件可以保存完全相同的图像,并在标题中添加链接:

    // AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED) 
    jQuery(function($) {
    $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, function(el) {
    return [el.href, el.title + '<br /><a href="' + el.href + '">
    Download this image</a>'];
    }, function(el) {
            return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
    });
    });

但是,我希望用户能够保存仅在名称中添加“lg”的高分辨率版本。

例如,不是下载显示的“image1.jpg”,而是下载“image1lg.jpg”

上面的代码使用 el.href 将图像加载到链接中,但如果我使用 + 'lg' 它会在 .jpg 后面添加它,所以我会得到“image1.jpglg”,它不起作用。

有没有办法删除el.href,然后从名称中减去“.jpg”,然后将“lg.jpg”添加到文件名中?

希望这是有道理的,谢谢你的时间。

【问题讨论】:

  • 是的,这只是基本的字符串操作。找到.jpg,删除它,用你想要的替换它。

标签: jquery autoload file-rename slimbox


【解决方案1】:

如果lg 始终是扩展名之前文件名的最后一部分,试试这个:

return [el.href, el.title + '<br /><a href="' + el.href.replace(/\.jpg$/i, 'lg.jpg') + '">Download this image</a>'];

【讨论】:

    【解决方案2】:

    我会使用 javascript 的 replace 函数。您可以匹配字符串或正则表达式并将其替换为您想要的任何内容,在这种情况下匹配“.jpg”并将其替换为“lg.jpg”。

    jQuery(function($) {
        $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, function(el) {
            return [el.href, el.title + '<br /><a href="' + el.href.replace('.jpg', 'lg.jpg') + '"> Download this image</a>'];
        }, function(el) {
            return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
        });
    });
    

    【讨论】:

      【解决方案3】:

      这个答案不是万能的答案,但它确实解决了您的具体问题。

      如果文件名有多个句点,此脚本将基本上失败

      是的,有一个 Javascript split() 函数:

      // The file
      var string = 'filename.jpg'
      
      // Split on periods
      var parts = string.split('.');
      
      // parts[0] = filename
      // parts[1] = jpg
      
      // Bring the string back together and add an 'lg' where needed
      var new_string = parts[0]+'lg.'+parts[1];
      

      【讨论】:

      • new_string 将是 filenamelgjpg。你没有替换 .
      • @RoryMcCrossan 谢谢! :)
      • @RoryMcCrossan 哈哈,这正是我在评论中使用@RoryMcCrossan 的原因
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多