[3, 4, 5]
['4', '1', 'abc123']
function combine_ids(ids){
return ids.join(',');
};
No matter what type of list, I want my function to return a string with single quotes around the elements.
The function should return:
'3','4','5'
and
'4','1','abc123'
I want my resulting string to have single quotes in them!
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string. Using this method, we can use apostrophes in strings built with ". 'We\'re safely using an apostrophe in single quotes. ' We can also use quotation marks in strings built with ".
JavaScript Array unshift() The unshift() method adds new elements to the beginning of an array. The unshift() method overwrites the original array.
Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
Simple logic!
function combine_ids(ids) {
return (ids.length ? "'" + ids.join("','") + "'" : "");
}
Example:
console.log(combine_ids([]));
console.log(combine_ids([3]));
console.log(combine_ids([3, 4, 'a']));
Example output:
(an empty string) '3' '3','4','a'
how do I put single quotes around an array I just “joined”?
Your approach seems to be unnecessarily complex. You better off:
toString
and quotedjoin
the intermediate array[03:22:35.728] [3, 4, 5].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:35.736] "'3','4','5'"
--
[03:22:58.925] ['4', '1', 'abc123'].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:58.933] "'4','1','abc123'"
Note: map
method required JS 1.6+, versions below are requiring you to iterate an array "manually":
function combine_ids( array ) {
var tmp = [];
for ( var i = 0; i < array.length; i++ ) {
tmp[i] = "'" + String( array[i] ) + "'";
}
return tmp.join(",");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With