如何将列表元素转换为字符串数组

时间:2016-05-22 10:42:02

标签: javascript

var categoryList="[Service,Ticket,Bill,Entertainment,Restaurant]";

我想将上面的String转换为String数组,如下所示: -

var categoryList=["Service","Ticket","Bill","Entertainment","Restaurant"];

任何解决方案都很明显。

4 个答案:

答案 0 :(得分:1)

categoryList = categoryList.replace(/\[|\]/g,"").split(",");

答案 1 :(得分:1)

您可以使用 slice() split()

var categoryList = "[Service,Ticket,Bill,Entertainment,Restaurant]"
  .slice(1, -1) // get `[` and `]`removed string
  .split(','); // split based on comma to get array

console.log(
  categoryList
)

答案 2 :(得分:0)

var yourString = "[Service,Ticket,Bill,Entertainment,Restaurant]"

var categoryList = yourString.substring(1, yourString.length-1).split(",") // removing [] and splitting with `,`

答案 3 :(得分:0)

使用String.match函数的另一个简短解决方案:

var categoryList="[Service,Ticket,Bill,Entertainment,Restaurant]";
console.log(categoryList.match(/\w+\b/g));  // ["Service", "Ticket", "Bill", "Entertainment", "Restaurant"]