Double nested quotes

拟墨画扇 提交于 2020-01-03 06:42:11

问题


I have this line of code

formsParent.innerHTML = "<p style = 'color: black; font-family: "Times New Roman" font-size: 2em'> Order submitted. Thank you for ordering! </p>"

The first quote is for the innerHTML property. Next is the properties inside the style attribute of the <p> element, and finally I need another quote inside this for the font-family property with a value that has multiple words so it also needs quotation marks. There are only "" and '', and using double quotes for the font-family throws an error. How do I use quotes inside quotes inside quotes?

EDIT: This is NOT a duplicate of the Double quote in JavaScript string. Stop flagging this!

In the above question, the OP asks for single-nested quotes - single quotes isnide double quotes was the answer or vice versa.

In my question, I ask for double-nested quotes - [quotes] inside [quotes] inside [quotes]. My question is an extra layer of quotes.


回答1:


In your case you'd need to escape the quotes:

formsParent.innerHTML = "<p style='color: black; font-family: \"Times New Roman\"; font-size: 2em'> Order submitted. Thank you for ordering! </p>";

But, in such cases it's better to use the backtick to contain the innerHTML value, thus you'd never need to escape the apostrophes nor the quotes:

formsParent.innerHTML = `<p style='color: black; font-family: "Times New Roman"; font-size: 2em'> Order submitted. Thank you for ordering! </p>`;



回答2:


The best option here would be to escape the quote chars:

formsParent.innerHTML = "<p style=\"color: black; font-family: 'Times New Roman' font-size: 2em\"> Order submitted. Thank you for ordering!</p>";



回答3:


Use a template literal

document.getElementById('formsParent').innerHTML = `<p style = 'color: red; font-family: "Times New Roman" font-size: 2em'> Order submitted. Thank you for ordering! </p>`
<div id="formsParent">


来源:https://stackoverflow.com/questions/52525674/double-nested-quotes

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