0

我有一个字符串

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>'

如何使用 javascript (no-jquery) 从 str 字符串获取 attr src?感谢!

4

3 回答 3

0

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

于 2013-06-10T04:59:56.750 回答
0

你可以这样做:

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/

确保字符串以第一个 childNode 开头,<iframe>或者第一个 childNode 是 textNode,这是行不通的。(如果您愿意,还有更强大的方法可以在这些情况下使用。)

于 2013-06-10T05:02:07.443 回答
0

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

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

/src="[^\ ]*"/i
于 2013-06-10T05:07:30.940 回答