Why cant i convert this arr
let stringarr = "[2022/07/12, 2022/08/09]"
to this arr
let arr = JSON.parse(stringarr) ---> error
Unexpected token / in JSON at position 5
what can i do then to convert it to an array
There are several ways to do that, if the format of the string stays like this. Here's an idea.
console.log(`[2022/07/12, 2022/08/09]`
.slice(1, -1)
.split(`, `));
Or edit to create a valid JSON string:
const dateArray = JSON.parse(
`[2022/07/12, 2022/08/09]`
.replace(/\[/, `["`)
.replace(/\]/, `"]`)
.replace(/, /g, `", "`));
console.log(dateArray);
Or indeed use the match method @Barmar supplied.
It's to much simple 😄.
As your input is a valid array in string format. So, remove [ ] brackets and split with comma (,). Then it automatically generates an array.
let stringarr = "[2022/07/12, 2022/08/09]";
let arr = stringarr.replace(/(\[|\])/g, '').split(',');
Output:
['2022/07/12', ' 2022/08/09']
let stringarr = "['2022/07/12', '2022/08/09']" let arr = JSON.parse(stringarr)error