Home > database >  How do i convert this string into an array type in - Javascript
How do i convert this string into an array type in - Javascript

Time:11-18

'[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]'

I tried using JSON.parse(string) But got Uncaught SyntaxError: Unexpected token 'b', "[b426be49-0"... is not valid JSON

I am expecting it to be :

[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]

without the strings around it.

CodePudding user response:

Just split with a regexp & then remove the empty items:

const s = '[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]'

const splitS = (s) => s.split(/[\[\],]/).filter(e => e)

console.log(splitS(s))

CodePudding user response:

You got the Uncaught SyntaxError: Unexpected token 'b', "[b426be49-0"... is not valid JSON error because the strings inside de array are not valid strings. You could do something like:

const myString = '[b426be49-0621-4240-821f-79bddf378e1e,c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf]';

const myStringWithoutBrackets = myString.substring(1, myString.length - 1);
const arrayOfStrings = myStringWithoutBrackets.split(',');

console.log(arrayOfStrings);
// Output: ['b426be49-0621-4240-821f-79bddf378e1e', 'c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf']

CodePudding user response:

you can use JSON.parse() to convert the string to an array.

console.log(JSON.parse("[\"b426be49-0621-4240-821f-79bddf378e1e\",\"c9e41cbb-b0d5-4833-bf72-0bf79ca31dcf\"]"))

  • Related