我有一个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/