简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM