How to wrap comma separated values string in single quotes? [closed]

蹲街弑〆低调 提交于 2021-02-08 12:00:33

问题


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.


回答1:


You can do it like below. Hope it helps.

var input = "label1, label2, label3, label4, label5";
var result = '\'' + input.split(',').join('\',\'') + '\'';



回答2:


"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(',');



回答3:


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]+"'";
    }
}



回答4:


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);


来源:https://stackoverflow.com/questions/34790745/how-to-wrap-comma-separated-values-string-in-single-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!