Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to disable parsing code in script tags using JavaScript DOMParser?

I have the following text file with JavaScript tags:

<script>
...
</script>
<script>
...
</script>
<script>
...
</script>

when I parse it like so:

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(`<root>${data}</root>`, "text/xml");
const tags = xmlDoc.getElementsByTagName("script");

I get an error because there are < and > symbols in JS program code, like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (let i = 0; i < tags.length; i++) {

I don’t want to replace < > with &lt; &gt; because those are also present inside strings in the code.

Is it possible to disable parsing code inside script tags?

>Solution :

For parsing HTML, we use the mime type text/html

const htmlDoc = parser.parseFromString(data, "text/html");
const tags = htmlDoc.getElementsByTagName("script");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading