Put quotes around a variable string in JavaScript

后端 未结 12 1955
时光说笑
时光说笑 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条回答
  • let's think urls = "http://example1.com http://example2.com"

    function somefunction(urls){
    var urlarray = urls.split(" ");
    var text = "\"'" + urlarray[0] + "'\"";
    }
    

    output will be text = "'http://example1.com'"

    0 讨论(0)
  • 2020-12-05 03:07
    var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
    

    Using escape sequence of " (quote), you can achieve this

    You can place singe quote (') inside double quotes without any issues Like this

    var text = "'http://www.ex.com';'http://www.ex2.com'"
    
    0 讨论(0)
  • 2020-12-05 03:08

    You can add these single quotes with template literals:

    var text = "http://example.com"
    var quoteText = `'${text}'`
    
    console.log(quoteText)

    Docs are here. Browsers that support template literals listed here.

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

    You can escape " with \

    var text="\"word\"";
    

    http://jsfiddle.net/beKpE/

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

    Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

    "http://example.com"
    
    0 讨论(0)
  • 2020-12-05 03:12

    This can be one of several solutions:

    var text = "http://example.com";
    
    JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')
    
    0 讨论(0)
提交回复
热议问题