0

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
  • You want to convert it into ('UYHN7687YTF09IIK762220G6','Second') to ["U", "Y", "H", "N", "7", "6", "8", "7", "Y", "T", "F", "0", "9", "I", "I", "K", "7", "6", "2", "2", "2", "0", "G", "6"] Provide details and write some code so that community will help rather than just asking answer Commented Aug 13, 2020 at 13:13
  • @Umashankar into array ['UYHN7687YTF09IIK762220G6','Second'] Commented Aug 13, 2020 at 14:16

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.