简体   繁体   English

使用Javascript为变量内的值添加单引号

[英]Adding the single string quote for value inside variable using Javascript

I have a variable, before I use that variable,I need to add string quotes to the value/data which is inside the variable using JavaScript need help 我有一个变量,在使用该变量之前,我需要使用JavaScript将字符串引号添加到变量内部的值/数据中,需要帮助

 //i am getting like this //
    var variable=king;

//i want to convert it with single quote//
     variable=variable;

but i need the data inside variable should be in a single quotation. 但是我需要变量内的数据应该用单引号引起来。

var x = 'abc';

var sData = "\\'" + x +"\\'"; var sData =“ \\'” + x +“ \\'”;

// sData will print "'abc'" // sData将显示“'abc'”

var x = 'pqr'; var x ='pqr'; var sData = "\\'" + x +"\\'"; var sData =“ \\'” + x +“ \\'”;

// sData will print "'abc'" // sData将显示“'abc'”

1) You can use doublequotes 1)您可以使用双引号

var variable = "'" + variable + "'";

2) ... or You can escape single quote symbol with backslash 2)...或者您可以使用反斜杠转义单引号

var variable = '\'' + variable + '\'';

You can concatenate the variable with your quotes like : 您可以将变量与引号连接起来,例如:

function addQuotes(value){
    var quotedVar = "\'" + value + "\'";
    return quotedVar;
}

And use it like : 并像这样使用它:

var king = addQuotes('king');  

console.log will display : console.log将显示:

'king'

Edit : you can try it in the chrome/firefox console, I did it and it works perfectly when copy/paste from here. 编辑:您可以在chrome / firefox控制台中尝试它,我做到了,当从此处复制/粘贴时,它可以完美工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM