Put quotes around a variable string in JavaScript

后端 未结 12 1956
时光说笑
时光说笑 2020-12-05 02:46

I have a JavaScript variable:

var text = \"http://example.com\"

Text can be multiple links. How can I put \'\' around the variable string?<

相关标签:
12条回答
  • 2020-12-05 03:16

    To represent the text below in JavaScript:

    "'http://example.com'"
    

    Use:

    "\"'http://example.com'\""
    

    Or:

    '"\'http://example.com\'"'
    

    Note that: We always need to escape the quote that we are surrounding the string with using \

    JS Fiddle: http://jsfiddle.net/efcwG/

    General Pointers:

    • You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

    Example

    var answer="It's alright";
    var answer="He is called 'Johnny'";
    var answer='He is called "Johnny"';
    
    • Or you can put quotes inside a string by using the \ escape character:

    Example

    var answer='It\'s alright';
    var answer="He is called \"Johnny\"";
    
    • Or you can use a combination of both as shown on top.

    http://www.w3schools.com/js/js_obj_string.asp

    0 讨论(0)
  • 2020-12-05 03:19

    Try:

    var text = "'" + "http://example.com" + "'";

    0 讨论(0)
  • 2020-12-05 03:19

    Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:

    function quote(text) {
      var urls = text.split(/ /)
      for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
      return urls.join(" ")
    }
    

    This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".

    It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.

    0 讨论(0)
  • 2020-12-05 03:26

    I think, the best and easy way for you, to put value inside quotes is:

    JSON.stringify(variable or value)
    
    0 讨论(0)
  • 2020-12-05 03:30

    In case of array like

    result = [ '2015',  '2014',  '2013',  '2011' ],
    

    it gets tricky if you are using escape sequence like:

    result = [ \'2015\',  \'2014\',  \'2013\',  \'2011\' ].
    

    Instead, good way to do it is to wrap the array with single quotes as follows:

    result = "'"+result+"'";

    0 讨论(0)
  • 2020-12-05 03:31
    var text = "http://example.com";
    
    text = "'"+text+"'";
    

    Would attach the single quotes (') to the front and the back of the string.

    0 讨论(0)
提交回复
热议问题