从字符串中取出图像标签,并将其放入数组中

时间:2019-04-28 17:44:29

标签: javascript regex

需要处理一个非常奇怪的字符串响应。我需要从该字符串中取出所有图像标签,并将它们放入数组中,这样我才能遍历数组,以便呈现图像

示例字符串

var str = '<p>↵   This is the cap you unscrew to open when you refuel your car↵</p>↵↵<p>↵ New line↵</p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵</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" />']

3 个答案:

答案 0 :(得分:0)

您可以使用.heading-wrapper { position: relative; } .heading-wrapper span { position: absolute; top: 0; left: 0; } /<img .*?>/g来检查匹配情况

exec

var str = '<p>↵   This is the cap you unscrew to open when you refuel your car↵</p>↵↵<p>↵ New line↵</p>↵↵<p>↵ <img alt="blah" src="https://www.imgone.com/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />↵</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)

答案 1 :(得分:0)

这是 img 标记

的JS正则表达式

<img\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>

JS演示

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

var result = str.match( /<img\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>/g );
console.log(result)

答案 2 :(得分:0)

您可以使用document.createElement()充当将所有HTML保留在str中的容器。将innerHTML设置为str的值后,您可以遍历刚创建的元素的children,过滤掉所有<image/>

已更新为递归获取元素

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

// Create a container for the HTML above
let el = document.createElement('div');
// Put string in innerHTML of container 
el.innerHTML = str;

// Function to recursively filter out any images (as document Nodes) 
getTags = (el, tagName) => Array.from(el.children).reduce((acc, node) => {
  if (node.children.length) {
    acc = [...acc, ...getTags(node, tagName)];
  } else if (node.tagName === tagName.toUpperCase()) {
    acc.push(node);
  }
  return acc;
}, []);

// Result
console.log(getTags(el, 'img'));

请不要使用正则表达式来解析HTML,请参阅this post