How to add single quote in the variable in Javascript?

给你一囗甜甜゛ 提交于 2019-11-27 06:40:25

问题


I have variable var str as following:

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';

回答1:


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 + "'";



回答2:


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>;'"



回答3:


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




回答4:


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

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!\"";



来源:https://stackoverflow.com/questions/10787393/how-to-add-single-quote-in-the-variable-in-javascript

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