Javascript - Parse a stringified arrays of strings

926 Views Asked by At

I have a string like so :

a= "['url1','url2','url3']"

coming from the server I want to convert it to array like :

arr = ["url1","url2","url3"]

but JSON.parse does not seems to be working and gives following error:

SyntaxError: Unexpected token ' in JSON at position 1

Thanks in advance.

3

There are 3 best solutions below

0
Martin Wahlberg On

You need to replace the single quotes with double quotes. An easy way to achieve this can be by replacing them with escaped quotes like this:

let validJSON = a.replace(/'/g, "\"")

JSON.parse(validJSON)
0
Simon Polak On

Your string needs to be in single quotes for JSON.parse to work in this example, also string representation in json uses double quotes as per standard.


JSON.parse('["url1","url2","url3"]')

0
Nick On

Try to use this code:

a = "['url1','url2','url3']"
urls = a.split(',')
arr = urls.map(url => url.replace(/'|\[|\]/g, ''))

console.log(arr) // ["url1", "url2", "url3"]

https://jsfiddle.net/z1frh8ys/