Arif
Arif

Reputation: 49

How to convert comma separated strings enclosed within bracket to array in Javascript?

How to convert below string to array in Javascript? The reason is that I want to take both value separately. The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')

var data = elm.value;
console.log(data);

Upvotes: 0

Views: 426

Answers (2)

Namysh
Namysh

Reputation: 4627

You can achieve this with regex, like this for example :

const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig

// Long way
const array = [];
let match;
while (match = regex.exec(string)){
  array.push(match[1]);
};
console.log(array)

// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))

source

Upvotes: 2

sazzad
sazzad

Reputation: 525

let given_string = "('UYHN7687YTF09IIK762220G6','Second')";

// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )

let expected_array = given_string.split(',');
console.log(expected_array);

Upvotes: 0

Related Questions