使用javascript从字符串中获取attr src

Get attr src from string using javascript

本文关键字:获取 attr src 字符串 javascript 使用      更新时间:2023-09-26

我有一个字符串

str = '<iframe width="100%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=vi&amp;geocode=&amp;q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;aq=&amp;sll=15.125395,108.795111&amp;sspn=0.034096,0.038581&amp;ie=UTF8&amp;hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;hnear=&amp;radius=15000&amp;t=m&amp;ll=21.011605,105.849323&amp;spn=0.048074,0.051498&amp;z=13&amp;output=embed"></iframe><br /><small><a href="https://maps.google.com/maps?f=q&amp;source=embed&amp;hl=vi&amp;geocode=&amp;q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;aq=&amp;sll=15.125395,108.795111&amp;sspn=0.034096,0.038581&amp;ie=UTF8&amp;hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;hnear=&amp;radius=15000&amp;t=m&amp;ll=21.011605,105.849323&amp;spn=0.048074,0.051498&amp;z=13" style="color:#0000FF;text-align:left">Xem Bản đồ cỡ lớn hơn</a></small>'

如何获得attr src使用javascript(无jquery)从字符串?谢谢!

试试这个:str.match(/.*src="([^"]+).*/)[1]

你可以这样做:

var str = '<iframe width="100%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=vi&amp;geocode=&amp;q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;aq=&amp;sll=15.125395,108.795111&amp;sspn=0.034096,0.038581&amp;ie=UTF8&amp;hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;hnear=&amp;radius=15000&amp;t=m&amp;ll=21.011605,105.849323&amp;spn=0.048074,0.051498&amp;z=13&amp;output=embed"></iframe><br /><small><a href="https://maps.google.com/maps?f=q&amp;source=embed&amp;hl=vi&amp;geocode=&amp;q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;aq=&amp;sll=15.125395,108.795111&amp;sspn=0.034096,0.038581&amp;ie=UTF8&amp;hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&amp;hnear=&amp;radius=15000&amp;t=m&amp;ll=21.011605,105.849323&amp;spn=0.048074,0.051498&amp;z=13" style="color:#0000FF;text-align:left">Xem Bản đồ cỡ lớn hơn</a></small>';
var div = document.createElement('div');
div.innerHTML = str;
alert(div.childNodes[0].getAttribute('src'));
http://jsfiddle.net/Dogbert/hxjpB/

确保字符串以<iframe>开头,或者第一个childNode将是textNode,这将不起作用。(如果你愿意的话,还有更健壮的方法可以在这些情况下工作。)

您可能会发现在代码中使用正则表达式很有趣:http://www.w3schools.com/jsref/jsref_obj_regexp.asp和http://www.w3schools.com/js/js_obj_regexp.asp

这个正则表达式应该可以工作:

/src="[^' ]*"/i