2

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

asked Jul 21, 2022 at 13:57
6
  • 3
    You need quotes around the dates. Commented Jul 21, 2022 at 13:58
  • 1
    @Barmar what if i dont have them. what can i do then to convert it to an array Commented Jul 21, 2022 at 13:59
  • 3
    Write your own parser, there's nothing built-in for this. Commented Jul 21, 2022 at 13:59
  • Fix the source of that data. It'll likely be much easier than writing a parser Commented Jul 21, 2022 at 14:00
  • Adding quotes wont work either tho let stringarr = "['2022/07/12', '2022/08/09']" let arr = JSON.parse(stringarr) error Commented Jul 21, 2022 at 14:01

4 Answers 4

5

It's not valid JSON, since the array elements aren't quoted.

If the array elements are all dates formatted like that, you could use a regular expression to extract them.

let stringarr = "[2022年07月12日, 2022年08月09日]"
let dates = stringarr.match(/\d{4}\/\d{2}\/\d{2}/g);
console.log(dates);

answered Jul 21, 2022 at 14:01
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Jul 21, 2022 at 14:04

Comments

0

const regexp = /\d+\/\d+\/\d+/g;
const stringarr = "[2022年07月12日, 2022年08月09日]";
const arr = [...stringarr.matchAll(regexp)];
console.log(arr)

answered Jul 21, 2022 at 14:26

Comments

0

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日']
answered Jul 21, 2022 at 22:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.