AnswerBun.com

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

Stack Overflow Asked by Arif on October 16, 2020

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

2 Answers

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

Correct answer by Namysh on October 16, 2020

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

Answered by sazzad on October 16, 2020

Add your own answers!

Related Questions

Serialise array as single XML element in C#

1  Asked on January 25, 2021 by david-poxon

   

How to Create a Function to extract data from a JSON file

1  Asked on January 25, 2021 by ineedhelp

 

SQL create aggregated result from 2 queries

2  Asked on January 25, 2021 by sudhishkr

         

Mongoose : find document with subdocument filter

1  Asked on January 25, 2021 by temp_user

     

problems with @binding between structs

1  Asked on January 24, 2021 by mateus-neves

 

Testing Saga using Jest that have other module dependencies

0  Asked on January 24, 2021 by mzafer

   

mysql join 3 table but the “COUNT” be duplicate

1  Asked on January 24, 2021 by faisal-budiman

         

FTPS failing, but only on some commands on some machines

1  Asked on January 24, 2021 by watyf

         

Differently displayed colors on chart.js

3  Asked on January 24, 2021 by leos-literak

     

Vue Js Dynamic Class Binding Not Updating

2  Asked on January 24, 2021 by niall-parker

   

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP