首页 > 解决方案 > 从字符串中取出图像标签并将其放入数组中

问题描述

需要处理一个很奇怪的字符串响应。我需要从该字符串中取出所有图像标签并将它们放入一个数组中,这样我就可以遍历该数组,以便渲染图像

示例字符串

var str = '<p>↵   This is the cap you unscrew to open when you refuel your car↵&lt;/p>↵↵<p>↵ New line↵&lt;/p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵&lt;/p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'

预期的结果可以是

['<img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />', '<img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />']

标签: javascriptregex

解决方案


您可以像这样使用/<img .*?>/gandexec来检查匹配

var str = '<p>↵   This is the cap you unscrew to open when you refuel your car↵&lt;/p>↵↵<p>↵ New line↵&lt;/p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵&lt;/p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'

var m;
var result = []
do {
    m = re.exec(str);
    if (m) {
        result.push(m[0]);
    }
} while (m);
//var tmp = str.replace(/<img .*?>/g,"");
console.log(result)

var re = /<img .*?>/g;
var str = '<p>↵   This is the cap you unscrew to open when you refuel your car↵&lt;/p>↵↵<p>↵ New line↵&lt;/p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵&lt;/p>Random Text <img alt="blah" src="https://www.imgtwo.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'

var m;
var result = []
do {
    m = re.exec(str);
    if (m) {
        result.push(m[0]);
    }
} while (m);
//var tmp = str.replace(/<img .*?>/g,"");
console.log(result)


推荐阅读