在JavaScript中将引号括在变量字符串周围

re1*_*man 26 javascript string jquery

我有一个JavaScript变量:

var text = "http://example.com"
Run Code Online (Sandbox Code Playgroud)

文字可以是多个链接.如何在变量字符串周围加上''?

我希望字符串,例如,看起来像这样:

"'http://example.com'"
Run Code Online (Sandbox Code Playgroud)

Sar*_*raz 46

var text = "\"http://example.com\""; 
Run Code Online (Sandbox Code Playgroud)

无论你的文字是什么,用它来包装",你需要把它们放在里面然后用它来逃避\.以上将导致:

"http://example.com"
Run Code Online (Sandbox Code Playgroud)

  • 丹的最高投票答案也没有描述,嗯.. http://stackoverflow.com/a/9671301/559850 (9认同)
  • 在这种情况下,也可以选票.还请告诉我您需要解释的内容? (8认同)

Aja*_*jai 23

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

text = "'"+text+"'";
Run Code Online (Sandbox Code Playgroud)

将单引号(')附加到字符串的前面和后面.


Sud*_*oti 9

尝试:

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


小智 6

您可以使用模板文字添加这些单引号:

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

console.log(quoteText)
Run Code Online (Sandbox Code Playgroud)

文档在这里。支持此处列出的模板文字的浏览器。


sla*_*oah 5

在JavaScript中表示以下文本:

"'http://example.com'"
Run Code Online (Sandbox Code Playgroud)

使用:

"\"'http://example.com'\""
Run Code Online (Sandbox Code Playgroud)

要么:

'"\'http://example.com\'"'
Run Code Online (Sandbox Code Playgroud)

请注意:我们总是需要使用\来转义包围字符串的引号。

JS小提琴:http//jsfiddle.net/efcwG/

一般指针:

  • 您可以在字符串内使用引号,只要它们与字符串周围的引号不匹配即可:

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Run Code Online (Sandbox Code Playgroud)
  • 或者,您可以使用\转义字符将引号放在字符串内:

var answer='It\'s alright';
var answer="He is called \"Johnny\"";
Run Code Online (Sandbox Code Playgroud)
  • 或者,也可以将两者结合使用,如顶部所示。

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


小智 5

我认为,对您来说,将价值放在报价内的最佳简便方法是:

JSON.stringify(variable or value)
Run Code Online (Sandbox Code Playgroud)