The version shown in your question has line breaks, which are not allowed in strings. You might have put them in for presentation here but make sure they are not in your actual code.
If you must use document.write
there's no need to escape anything in your quotted string argument of document.write
(if it contained the same quote marks as you use to quote it, they would need to be escaped but tags etc. are fine).
Although I can't see why the command specified in the 'created' script inside your your conditional cannot simply be placed directly in your conditional (without needing to write a new script to the page), if I had to add a script created by a script, I would create a new script element, add innerText to it specifying the required commands, and then append the the script element to the document.
If your added script needs to be placed at a specific part of the page (rather than appended as the last child of the body as in my example) you can learn more here: How to append a childnode to a specific position
The following example has a single script which creates a new script with a single command to change the page background color. CSS has been used to show the actual scripts in the rendered html (for presentation only, irrelevant to function). You will see that the created script is added to the page and executed.
let newScript = document.createElement('script');
newScript.innerText = "document.body.style='background: red';";
document.body.appendChild(newScript);
body {
background: blue;
}
/*make scripts visible in html*/
script {
display: inline-block;
border: 1px solid black;
padding: 10px;
white-space: pre-wrap;
font-family: monospace;
color: #00ff00;
background: #005500;
margin-bottom: 20px;
}
<h1> page with a single script</h1>
<p>The background color of the page is set to BLUE in the accompanying style sheet</p>
<p>This page has a single script tag included in its html. The script creates a new script element, adds a command to it, and appends the script to the page</p>
<p>the script added by js then changes the page background to red</p>
<p>both scripts are shown below in the rendered html (because the accompanying styles make them visible) but only the first one is written as a script in the original html</p>