Reputation: 33
I have to programmatically remove all iframes form a string that contais raw html base on the source of that iframe. Eg: "... "
This is in a javascript string. I thought about using String.replace based on some regex that excludes or some other approach.
Just need an example or some ideas, hope someone can help me because I am stuck with this and can't think about a propper solution.
Eg:
const regex = /Some weird regex to select the iframe piece/g
//Which I don't know how to write
// Happy to use something that removes all iFrames from the code as a quickfix regardless of the url
const raw_html = "\<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> ... \</html\>"
raw_html.replace(regex, '')
//This would remove whatever was on that regex with an empty piece of string.
If anyone has any ideas, they are welcome. Thanks in advance
I've tried something like the example above, but couldn't write a working regex expression
Upvotes: 3
Views: 470
Reputation: 137
Try this ↓↓↓
let html = '<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> <h2>Just another element to test the regex</h2> <p1>hello</p1> ... \</html\>';
let regex = /\n*\s*<iframe.*?\\?>.*?<\/iframe\\?>\s*\n*/gi;
html = html.replace(regex, '');
console.log(html);
If you will ever need to remove a different element, you can use this function:
function removeElementFromHtmlString(element, htmlStr) {
return htmlStr.replace(new RegExp(`\\s*<${element}.*>(?:.*<\\/${element}>)?`, 'g'), '');
}
let html = '<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> <h2>Just another element to test the regex</h2> <p1>hello</p1> ... \</html\>';
console.log(removeElementFromHtmlString('h2', html));
console.log(removeElementFromHtmlString('p1', html));
Upvotes: 2