简体   繁体   English

如何在 JavaScript 中容纳包含单引号和双引号的字符串

[英]How can I accommodate a string with both single and double quotes inside of it in JavaScript

I have an application, and it is fed some HTML.我有一个应用程序,它提供了一些 HTML。 It then needs to put that HTML into a string.然后它需要将 HTML 放入一个字符串中。 This HTML contains single and double quotes.这个 HTML 包含单引号和双引号。 Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?是否有可能在 javascript 中声明一个包含信息的字符串,不使用单引号或双引号?

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.请记住,此字符串的一部分将是 JavaScript,我稍后将需要执行它。

You need to escape the quotation characters with \ :您需要使用\转义引号字符:

var someString = 'escape all the quotation marks \"\'';

Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?是否有可能在 javascript 中声明一个包含信息的字符串,不使用单引号或双引号?

No. JavaScript string literals are delimited with either single quotes or double quotes.编号 JavaScript 字符串文字用单引号或双引号分隔。 Those are the only choices.这些是唯一的选择。

does anyone know a simple and easy way to escape these quotes so I can put it in a string?有谁知道一种简单的方法来逃避这些引号,所以我可以把它放在一个字符串中?

Do you mean in a string literal?你的意思是字符串文字吗?

var str = "var foo=\"bar\"; function say(it) { alert('It is: ' + it); say(foo);";

Or programmatically?还是以编程方式?

str = str.replace(/"/g, '\\"');

An easy way to escape the quotes is to use the javascript escape function.转义引号的一种简单方法是使用 javascript 转义 function。

http://www.w3schools.com/jsref/jsref_escape.asp http://www.w3schools.com/jsref/jsref_escape.asp

Use the escape function to replace special characters (including single and double quotes).使用escape function 替换特殊字符(包括单引号和双引号)。 You can then use the unescape function to return the string to it's normal state later if necessary.然后,如有必要,您可以稍后使用unescape function 将字符串返回到正常的 state 。

For example:例如:

var data = 'hello my name is "James"';
alert(escape(data)); //Outputs: hello%20my%20name%20is%20%22James%22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM