-4

'[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.

roqkabel
  • 21
  • 4
  • 5
    What you're expecting it to be is not valid JavaScript. Can the source of this data be corrected to produce valid JSON? – David Nov 18 '22 at 14:28
  • 1
    Try RegExp to fetch string out of it and put it into an array. – MORÈ Nov 18 '22 at 14:29
  • 1
    *...without the strings around it* — those are quote characters, not "strings". You have little choice but to transform your current string into an array of two strings. – Pointy Nov 18 '22 at 14:30
  • Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212), how to [access properties](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_Accessors), and use the static and instance methods of [`Array`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). [`JSON.parse`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) would be the correct choice if your string was valid JSON; if it’s possible to make it valid JSON, that’s the preferable approach. – Sebastian Simon Nov 18 '22 at 14:37
  • Otherwise, use the [`String`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods) and [`RegExp`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp#instance_methods) methods. Make sure you understand what [array literals](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#array_literal_notation) are and what [strings](//developer.mozilla.org/en/docs/Glossary/String) are. – Sebastian Simon Nov 18 '22 at 14:37

2 Answers2

5

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))
muka.gergely
  • 8,063
  • 2
  • 17
  • 34
0

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']
Mauro Vinicius
  • 761
  • 7
  • 13