如何提取embed标签的src属性

问题描述 投票:1回答:2

如何用正则表达式提取嵌入标签的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;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;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;amp;hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>

是否有可能只获得src属性的值?

谢谢!

javascript regex
2个回答
2
投票

请不要在没必要的地方使用正则表达式...

var htmlcode = '<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>';

div = document.createElement('div');
div.innerHTML = htmlcode ;
var yourSrc = div.getElementsByTagName('embed')[0].src;

2
投票

除了已经提到的DOM方法之外,如果已经包含它(OP没有提到),你也可以使用jQuery为你做这个:

var htmlcode = '<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>';
var yourSrc = jQuery(htmlcode).find('embed').prop('src');
© www.soinside.com 2019 - 2024. All rights reserved.