Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove iframe from string with JavaScript and Regexv

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

like image 505
Paulo Amaral Avatar asked Jun 02 '26 05:06

Paulo Amaral


1 Answers

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));
like image 161
thisistemporary Avatar answered Jun 04 '26 17:06

thisistemporary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!