正则表达式将 html-image 转换为 XML 以避免预加载

Regex to convert html-image to XML to avoid preloading

本文关键字:加载 XML html-image 转换 正则表达式      更新时间:2023-09-26

我目前正在通过ajax将XML提要拉入Web应用程序。显然我喜欢使用 jquery 来解析它,如下所示:

$(source).find("item"); 

这样做的问题是所有内容都转换为节点,包括 -tags。考虑到这是某种 RSS 提要,并且提要包含完整的文章(包括图片库),有许多 img 标签。为了防止这种情况,我想尝试将 img 标签转换为这样的东西:

以前:

<img src="path_to_img.jpg" width="450" height="199" alt="alt description" title="image title" class="image_classes" />

后:

<image>
<src>path_to_img.jpg</src>
<alt>alt description</alt>
<title>image title</title>
<class>image_classes</class>
</image>

如果有人有比使用正则表达式更好的建议,当然也欢迎这些建议。但是由于必须将其视为文本,因此考虑到图像在添加到DOM时开始预加载,我担心很少。

好吧,除非你能保证所有这些属性将始终存在,并且总是在引号字符串等中,否则这并不容易。

var html = '<img src="path_to_img.jpg" width="450" height="199" alt="alt description" title="image title" class="image_classes" />';
var regex = /<img .*?(src|alt|title|class)="([^"]*)" .*?(src|alt|title|class)="([^"]*)" .*?(src|alt|title|class)="([^"]*)" .*?(src|alt|title|class)="([^"]*)".*?'/?>/g;
var xmlTemplate = '<image><$1>$2</$1><$3>$4</$3><$5>$6</$5><$7>$8</$7></image>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​';
var xml = html.replace(regex, xmlTemplate);

如果您的源 HTML 不那么统一,则可能必须使用 .replace(regex, func) 而不是 .replace(regex, string)

正如您所说,alt 属性可能不存在,那么您需要使用带有函数的正则表达式,如下所示:

var html = '<img src="path_to_img.jpg" width="450" height="199" alt="alt description" title="image title" class="image_classes" />';
var regex = /<img .*?>/gi;
function getAttributeValue(tag, attribute)
{
    var regex = new RegExp('''b' + attribute + '="([^"]*)"', 'i');
    var match = tag.match(regex);
    return ''t<' + attribute + '>' + (match ? match[1] : '') + '</' + attribute + '>'n';
}
var xml = html.replace(regex, function($0)
{
    var xml = '<image>'n';
    xml += getAttributeValue($0, 'src');
    xml += getAttributeValue($0, 'alt');
    xml += getAttributeValue($0, 'title');
    xml += getAttributeValue($0, 'class');
    xml += '</image>';
    return xml;
});

这是前两个属性 src 和 alt 的示例:

HTMLstring.replace(new RegExp("<img src='"([^'"]+)'".*alt='"([^'"]+)'"","gm"), "<image><src>$1</src><alt>$2</alt></image>")

如果您预见到某些属性可能会丢失,您可以使用 | 运算符来管理所有备选方案,或者可以采用混合方法,从 img 标签中提取一组键值对,然后将它们与一些 js 连接在一起:

    $.each(HTMLstring.replace(/<img ([^ =]+)="([^"]+).*'/>/), function () {
        <do_what_you_need_with($1, $2)>
    });
如果您

不介意将alt标签完全排除在xml之外,如果它不存在在html中,那么您可以使用以下内容:

var regex = /'s+(src|alt|title|class)'s*='s*"([^"]+)"/gi;
var res;
var xml = '<image>'n';
while ((res = regex.exec(html)) !== null) {
    xml += "'t<" + res[1] + ">" + res[2] + "</" + res[1] + ">'n";
}
xml += "</image>";