Search code examples
javascriptquotes

How to add single quote in the variable in Javascript?


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

Solution

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