从没有jQuery的字符串中获取Image src

时间:2013-10-29 14:55:11

标签: 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的情况下实现同样的目标?

3 个答案:

答案 0 :(得分:3)

嗯,你想对它进行一些简单的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

答案 1 :(得分:1)

你可以通过以下方式获得:

var i = '<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>';
    alert(i.substring(i.indexOf('http'), i.lastIndexOf('"')));

答案 2 :(得分:0)

我可以看到您在img中使用此div。将id中的div参数设置为id="imgDiv"。然后您可以使用此语法来解决问题:

<script>
  var div = document.getElementById("imgDiv");
  var image = div.getElementsByTagName("img")[0];
  alert(image.src);
</script>