2

I have the following example of a string:

"label1, label2, label3, label4, label5"

Now, because this will be used as an object initialising a jquery plugin, it needs to look like this:

'label1','label2','label3','label4','label5'

I already managed to split the string with split(","), turning it into an array, however i am not sure how i can wrap each of the array items with single quotes, at which stage, i will be able to join it back to a string for usage?

Any ideas?

solution can be js only or jquery.

4
  • 2
    What plugin are you talking about? Perhaps it accepts JSON object or Array as parameter
    – Lashus
    Jan 14, 2016 at 13:28
  • 1
    It sounds quite wrong, that a jQuery plugin requires a "well-formed" string as input. More likely it needs an array or object.
    – Sirko
    Jan 14, 2016 at 13:29
  • Please show how you are initialising the plugin. Does the plugin only take 1 string? I only ask because jquery plugins are normally initialised with a configuration object rather than a single string.
    – Phil
    Jan 14, 2016 at 13:31
  • I like all the downvotes for no apparent reason. Can you please explain them? Some plugins/present code in projects sometimes can be quite finicky, i know it sounds like a dumb question.
    – geodeath
    Mar 9, 2016 at 17:00

4 Answers 4

12

You can do it like below. Hope it helps.

var input = "label1, label2, label3, label4, label5";
var result = '\'' + input.split(',').join('\',\'') + '\'';
1
  • All replies were great, but this is my preferred solutions, cheers!
    – geodeath
    Jan 14, 2016 at 13:58
3
"label1, label2, label3, label4, label5".split(',').map(function(word){
    return "'" + word.trim() + "'";
}).join(',');

(ES6 edit)

"label1, label2, label3, label4, label5".split(',')
   .map(word => `'${word.trim()}'`)
   .join(',');
2
  • You missed a space after the ',' in your split call. Upvoted! Jan 14, 2016 at 13:31
  • I've added .trim() to get rid of the space, might as well have used .split(/,\s*/).
    – pawel
    Jan 14, 2016 at 13:32
1

Maybe somthing like this:

var str = "label1, label2, label3, label4, label5";
var arr = str.split(",");

for (var i in arr) {
    if (arr.hasOwnProperty(i)) {
        arr[i] = "'"+arr[i]+"'";
    }
}
1

Split string with comma and space to make array and use join method to get array element separated by separator. i.e: separator as ',' and also add start and end quote because it is missing after joining elements.

var str = "label1, label2, label3, label4, label5";
var res = str.split(", ");
var data = "'" + res.join("','") + "'";
console.log(data);

Not the answer you're looking for? Browse other questions tagged or ask your own question.