如何用正则表达式提取嵌入标签的src
属性?
在此示例中(youtube视频):
<div dir="" class="ms-rtestate-field">
<div class="ExternalClass082784C969B644B096E1F293CB4A43C5">
<p>
<object width="480" height="385">
<param name="movie" value="http://www.youtube.com/v/Ora35AzLxt0?fs=1&amp;hl=fr_FR"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/Ora35AzLxt0?fs=1&amp;hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>
</object>
</p>
</div>
</div>
我只能用这个正则表达式提取完整的标签:
<embed>*(.*?)</embed>
结果:
<embed src="http://www.youtube.com/v/Ora35AzLxt0?fs=1&amp;hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>
是否有可能只获得src
属性的值?
谢谢!
请不要在没必要的地方使用正则表达式...
var htmlcode = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/Ora35AzLxt0?fs=1&hl=fr_FR"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/Ora35AzLxt0?fs=1&hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
div = document.createElement('div');
div.innerHTML = htmlcode ;
var yourSrc = div.getElementsByTagName('embed')[0].src;
除了已经提到的DOM方法之外,如果已经包含它(OP没有提到),你也可以使用jQuery为你做这个:
var htmlcode = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/Ora35AzLxt0?fs=1&hl=fr_FR"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/Ora35AzLxt0?fs=1&hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
var yourSrc = jQuery(htmlcode).find('embed').prop('src');