I have an array like this
var array = ["f","test"];
var string =array.toString();
excepted string var string ='f','test';
current value: f,test
I have an array like this
var array = ["f","test"];
var string =array.toString();
excepted string var string ='f','test';
current value: f,test
- please fix the typo and add a bit more info or context – Montagist Commented Apr 27, 2017 at 7:54
- Writing this question took so much more time than simply googling the answer. Why? – 1252748 Commented Apr 28, 2017 at 13:56
6 Answers
Reset to default 10You almost had it. Try this:
array.map(x => "'" + x + "'").toString();
Variable names like array and string are probably...akin to bad etiquitte, but I got'chu:
var anArray = [ "f", "test" ];
var theString = "'" + anArray.join("','") + "'";
Using ES6 with string interpolation and arrow function.
You can use join()
or toString()
to display each item separated by a comma
var array = ["f","test"];
console.log(array.map(x=>`'${x}'`).join(','))
console.log(array.map(x=>`'${x}'`).toString())
Let's use Map in JS
var result = ["f","test"].map(function(b) {
return "'" + b + "'";
});
console.log(result.toString());
1. using JavaScript Array.join() method : It will join all elements of an array into a string.
DEMO
var array = ["f","test"];
var res = "'"+array.join("','")+"'";
console.log(res);
2. using ES6 spread(...) operator : It allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
DEMO
let array = ["f","test"];
function printString(a,b) {
var str = `'${a}','${b}'`;
return str;
}
var res = printString(...array);
console.log(res);
3. using Array.map() method with ES6 syntax - It creates a new array with the results of calling a provided function on every element in this array.
DEMO
var array = ["f","test"];
var str = array.map(item => "'" + item + "'").join();
console.log(str);
I believe you want your ouptut as a string and not as array and code to be written such that it is supported by all browser (no ES6). So I have tried to keep it as simple as possible:
var arrayTest = ["f","test"]
var str = arrayTest.map(function(obj) {return("'" + obj + "'")}).toString();