【问题标题】:Getting an src url without the file extension获取没有文件扩展名的 src url
【发布时间】:2013-12-26 21:07:54
【问题描述】:

我有这行代码供 jQuery 获取图像$(this).find("img").attr("src")src 所以,我相信你们都知道它会返回类似http://www.mysite.com/this.image.png 的东西

是否有任何这样的声明可以让我在没有文件扩展名的情况下获取 url,所以:http://www.mysite.com/this.image 所以我可以在 url 中添加一些内容,例如 pview 用于图像预览文件或 big 用于大型图片等

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 使用字符串操作?
  • var src = "http://www.mysite.com/this.image"; src.substr(0, src.lastIndexOf("."));
  • @Givi 不要忘记将第二部分分配给一个新变量(或返回src)。

标签: javascript jquery


【解决方案1】:

试试这个:

 var img = $(this).find("img").attr("src");  
 img = img.substring(0,img.lastIndexOf("."));

【讨论】:

  • 什么是错误......让我检查方法,我假设 img 是一个有值的字符串?
  • 错误提示 Uncaught TypeError: Cannot call method 'lastIndexOf' of undefined。哦,实际上我犯了一个错误,我在我的方法之外调用了$(this),所以它不知道this 是什么。
  • 是的,听起来 var img 不包含字符串值。
【解决方案2】:

查看 this 教程以了解 JavaScript substring() 函数。它允许您从字符串中提取字符。它应该看起来像这样(未经测试):

var url = $(this).find("img").attr("src");
var urlLength = url.length -4; //The -4 is for the last 4 chars. Example ".png"
url = url.substring(0, urlLength);

我希望这会有所帮助!

【讨论】:

    【解决方案3】:

    你可以使用:

    var url   = $(this).find("img").attr("src");
    var parts = url.match(/(.*)\.([^\\/]+)$/);
    console.log(parts[0]); # => http://www.mysite.com/this.image
    console.log(parts[1]); # => png
    console.log(parts[0] + '.big.' + parts[1]);
    #=> http://www.mysite.com/this.image.big.png
    

    正则表达式解释:

    (.*)        // capture all the characters before
    \.          // .. a dot character
    ([^\\/]+)$  // capture any characters afterwards (that are not `\` or `/`)
    

    【讨论】:

    • 你能详细说明你的正则表达式吗?
    • 很好的答案,我真的很喜欢有一个带有子字符串的数组的想法,但由于某种原因,我只是不懂正则表达式,我将使用相同的文件扩展名,所以我选择了而是 substring 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2016-12-05
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多