Javascript 如何在Javascript中的变量中添加单引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10787393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:55:33  来源:igfitidea点击:

How to add single quote in the variable in Javascript?

javascriptquotes

提问by Acubi

I have variable var stras following:

我有var str如下变量:

var str = <option value="1">tea</option>;

I would like to make it as below

我想让它如下

var quote_str = '<option value="1">tea</option>;'

Is there anyone can help me? Thanks in advance!

有没有人可以帮助我?提前致谢!

Edit:

编辑:

I have tried the following code,however, it's not correct.

我已经尝试了以下代码,但是,它不正确。

var quote_str =  'str';

回答by Guffa

I think that you want the semicolon outside the string literal:

我认为你想要字符串文字之外的分号:

var quote_str = '<option value="1">tea</option>';

If you mean that you want apostrophe characters inside the string also, you can use \'to put an apostrophe in a string delimited by apostrophes:

如果您的意思是还希望在字符串中包含撇号字符,则可以使用\'将撇号放入由撇号分隔的字符串中:

var quote_str = '\'<option value="1">tea</option>\'';

You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:

您还可以使用引号来分隔字符串。那么你不必转义撇号,但你必须转义引号:

var quote_str = "'<option value=\"1\">tea</option>'";

If you already have a string, and want to add apostrophes around it, you concatenate strings:

如果您已经有一个字符串,并且想要在它周围添加撇号,您可以连接字符串:

var quote_str =  "'" + str + "'";

回答by Eliran Malka

Escape each single quote with a back-slash:

用反斜杠转义每个单引号:

var quote_str = '\'<option value="1">tea</option>;\''

…or wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:

...或用不同类型的引号(即双引号)包裹字符串,但一定要转义内部双引号,以免无意中关闭字符串:

var quote_str = "'<option value=\"1\">tea</option>;'"

回答by Akhila Antony

We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.

我们可以使用反斜杠 () 转义字符来防止 JavaScript 将引号解释为字符串的结尾。

The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

\' 的语法永远是单引号,\" 的语法永远是双引号,不用担心打断字符串。

Using this method, we can use apostrophes in strings built with ".

使用这种方法,我们可以在用“.”构建的字符串中使用撇号。

'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".

'我们在单引号中安全地使用撇号。' 我们也可以在用 " 构建的字符串中使用引号。

"Then he said, \"Hello, World!\"";

"然后他说,\"你好,世界!\"";

回答by Adam Sweeney

You can escape characters in Javascript with the \. If that's your issue

您可以使用 .js 转义 Javascript 中的字符\。如果那是你的问题