Вы можете использовать для 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, см. этот пост .