Using quotation marks in Javascript with innerHTML

五迷三道 提交于 2019-12-01 20:01:55
ItsGreg

You have to escape them with \.

"This is a string with \"quotation\" marks."

How to include quotes in a string

Choose one type of quote as the wrapper, e.g. ", then for attribute wrappers, use the other, e.g. '. If you then need any other embedded quotes, escape them like so \'.

document.getElementById("storybox").innerHTML = "Initially she fails to notice you and stares into the distance with dazed look of someone who has considered the exact point at which the universe might have ended, present within a kind of altered dimensionality that places her materially at a similar point of existence to you, while leaving her utterly absent from it in some other, more absolute sense. Two nuns scurry past her, heading towards a small, fluffy dog, who they pet while making cooing sounds; a stern man in an ill-fitting police officer\'s uniform eyes them suspiciously. This spectacle seems to rouse her from her trance, and she looks quizzically at them, tilting her head to one side, before spotting you out of the corner her eye and waving you over.</p><p>When you arrive at the hotel it is empty but for two bleary eyed reception staff who stare as you walk past. Deer-Wolf tells you this is the place where the murderer lives. He rents a different room each week, always under different assumed names. He tells people this is because he is married, and likes to take women back unnoticed. The staff have never seen one leave, but the room is always impeccably kept, so the uneasy feeling the hotel staff have about him has never yet been officially corroborated.</p>";

For future reference: please make more concise examples.

Since this is HTML, I'd try using &quot; in the string.

Qwertiy

function test1() {
  eval("console.log('\'text\'')");
}

function test2() {
  eval("console.log(\"'text'\")");
}

function test3() {
  eval("console.log('\\'text\\'')");
}
button {
  margin-bottom: .25em;
}
<button onclick="console.log("'text'")">Wrong</button>
<button onclick='console.log("'text'")'>Wrong too</button>
<br>
<button onclick="console.log(&quot;'text'&quot;)">Right</button>
<button onclick='console.log("&#39;text&#39;")'>Right too</button>
<button onclick="console.log(&quot;&#39;text&#39;&quot;)">And this one is right</button>
<br>
<button onclick="console.log('\'text\'')">Right with escaping</button>
<br><br>
<button onclick="test1()">Wrong in js</button>
<br>
<button onclick="test2()">Escaping outer in js</button>
<button onclick="test3()">Escaping inner in js js</button>
<br><br>
<button onclick=console.log("'text'")>And the final one - this way works too</button>

More information (in Russian): https://ru.stackoverflow.com/a/456039/178988

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!