如何在 JavaScript 中容纳包含单引号和双引号的字符串
我有一个应用程序,它提供了一些 HTML。然后需要将该 HTML 放入字符串中。此 HTML 包含单引号和双引号。在javascript中,是否可以声明一个内部包含信息的字符串,并且不使用单引号或双引号?
我想如果不可能的话,有谁知道一种简单易行的方法来转义这些引号,以便我可以将其放入字符串中?请记住,该字符串的一部分将是我稍后需要执行的 JavaScript。
I have an application, and it is fed some HTML. It then needs to put that HTML into a string. This HTML contains single and double quotes. Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?
I guess if it is not possible, does anyone know a simple and easy way to escape these quotes so I can put it in a string? Keep in mind, part of this string will be JavaScript that I will later need to execute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用
\
转义引号字符:You need to escape the quotation characters with
\
:不可以。JavaScript 字符串文字用单引号或双引号分隔。这些是唯一的选择。
你的意思是字符串文字吗?
还是以编程方式?
No. JavaScript string literals are delimited with either single quotes or double quotes. Those are the only choices.
Do you mean in a string literal?
Or programmatically?
转义引号的一个简单方法是使用 javascript 转义函数。
http://www.w3schools.com/jsref/jsref_escape.asp
An easy way to escape the quotes is to use the javascript escape function.
http://www.w3schools.com/jsref/jsref_escape.asp
使用
escape
函数来替换特殊字符(包括单引号和双引号)。如果需要,您可以稍后使用 unescape 函数将字符串返回到正常状态。例如:
Use the
escape
function to replace special characters (including single and double quotes). You can then use theunescape
function to return the string to it's normal state later if necessary.For example:
我知道这是一个老问题,但有一种处理它的方法,这里还没有人提出,它是 模板文字。基本上,这个符号 (`),称为反引号。它们的工作方式与单引号和双引号相同,但增加了多行支持。
例如,下面的字符串包含两种引号类型。使用反引号可以解决问题:
由于反引号不常用(或在键盘上找到),因此它不会导致任何问题。
编辑:Nvm。键盘上有反引号。但仍然不是很常用。
I know that this is an old question but there is a way of handling it that no one here brought up yet and it's template literals. Basically, this symbol (`), known as backticks. They work the same way as single and double quotes, with the addition of multi-line support.
For example, the below String contains both quote types. Using backticks, this fixes the problem:
Since backticks aren't commonly used (or found on the keyboard), it shouldn't cause any issues.
EDIT: Nvm. Backticks are on the keyboard. Still not very commonly used though.