···11+---
22+title: "TIL: you need to escape the </script> in a string in an inline script in HTML"
33+date: 2024-02-03
44+type: blog
55+hero:
66+ ai: "Photo by Xe Iaso, iPhone 13 Pro"
77+ file: winter-drive
88+ prompt: "A color-graded image of a snowy field taken from the side of a moving car."
99+---
1010+1111+When I was implementing [this change](https://github.com/Xe/site/commit/944fbf678403c77e158accd66363accbbe6d6eb4) in my site, I ran into a weird issue where my literal JavaScript text was being inserted into the page as if it was in the literal HTML. This was odd at first, but then I realized what was going on.
1212+1313+I was converting code that looked like this:
1414+1515+```html
1616+<script src="https://ethical-ads.whatever/script.js" async></script>
1717+<div
1818+ data-ea-publisher="christinewebsite"
1919+ data-ea-type="text"
2020+ data-ea-style="fixedfooter"
2121+></div>
2222+```
2323+2424+Into something like this:
2525+2626+```html
2727+<script>
2828+ if (!window.location.hostname.includes(".shark-harmonic.ts.net")) {
2929+ document.write('<script src="https://ethical-ads.whatever/script.js" async></script>');
3030+ }
3131+</script>
3232+<div data-ea-publisher="christinewebsite" data-ea-type="text" data-ea-style="fixedfooter"></div>
3333+```
3434+3535+But then I saw `'); }` at the top of every page. This was odd, but when I figured out what was going on, I felt very dumb. I was writing a string that contained a `</script>` tag, which was causing the browser to think that the script tag was ending early.
3636+3737+The fix was simple: escape the `</script>` tag in the string. This is done by replacing the `/` with `\/`:
3838+3939+```html
4040+<script>
4141+ if (!window.location.hostname.includes(".shark-harmonic.ts.net")) {
4242+ document.write(
4343+ '<script src="https://ethical-ads.whatever/script.js" async><\/script>'
4444+ );
4545+ }
4646+</script>
4747+<div
4848+ data-ea-publisher="christinewebsite"
4949+ data-ea-type="text"
5050+ data-ea-style="fixedfooter"
5151+></div>
5252+```