Swadhin
Swadhin

Reputation: 3

How to convert list elements to string array

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

I want to convert the above String as String array like below:-

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

Any Solution is appreciable.

Upvotes: 0

Views: 48

Answers (4)

user6360214
user6360214

Reputation:

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

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use slice() and 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
)

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Another short solution using String.match function:

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

Upvotes: 0

Pawan B
Pawan B

Reputation: 4623

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

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

Upvotes: 0

Related Questions