javascript - 不使用 jQuery 从字符串获取图像 src

标签 javascript html

我有一个STRING(不在我的文档中),例如

<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg"> Freedom is a wonderful thing and the folks at BearExtender want Microsoft users to enjoy more of it. Its new 1,200mW USB WiFi booster for PCs finally caught up with the Mac version, which extends WiFi range up to four times more than usual. One lucky reader will get to savor this new found freedom ...<div>

我想去掉字符串中第一个图像的源。我知道我可以使用 jquery 来做到这一点: String.find('img').first().attr('src');

如果没有jquery,我怎样才能实现同样的事情?

最佳答案

好吧,你想对其进行一些简单的 JS 测试,以从那里删除 src,如下所示:

var str = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg"> Freedom is a wonderful thing and the folks at BearExtender want Microsoft users to enjoy more of it. Its new 1,200mW USB WiFi booster for PCs finally caught up with the Mac version, which extends WiFi range up to four times more than usual. One lucky reader will get to savor this new found freedom ...<div>'

var imgExists = str.indexOf('<img src="');

if (imgExists > -1) {
    var i = imgExists + 10;

    str = str.substr(i);
    str = str.substr(0, str.indexOf('"'));
    alert(str); 
     // returns = http://www.blogcdn.com/www.engadget.com/media/2013/10/bear-extender-    samsungativ_thumbnail.jpg 

    // to remove all the spaces you might also want to do another replace after the last 2 substr's
    // str = str.replace(/\s/g, ''); 
}

<强> jsFiddle DEMO

关于javascript - 不使用 jQuery 从字符串获取图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661680/

相关文章:

javascript - 使用对象字面量而不是 switch 语句

javascript - Node.js - 使用 ejs 的动态列表

html - CSS需要申请html文件的不同部分

html - 将验证码控件包装在 p 标签中,如何将其向右移动?

javascript - 在jsp中如何执行带条件的onload?

html - 随着最大高度的变化响应图像缩放

javascript - JQuery:表单验证 - 没有得到任何结果

JavaScript - 在 Canvas 上绘图时鼠标位置错误

javascript - 有没有办法为隔离范围别名提供默认值?

javascript - 为什么我的 jscript 在单击 anchor 链接后开始出错