Put quotes around a variable string in JavaScript

后端 未结 12 1978
时光说笑
时光说笑 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: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.

提交回复
热议问题