简体   繁体   English

将数组的字符串转换为数组js

[英]Convert a string of an array to an array js

Why cant i convert this arr为什么我不能转换这个 arr

let stringarr = "[2022/07/12, 2022/08/09]"

to this arr到这个arr

let arr = JSON.parse(stringarr) ---> error

Unexpected token / in JSON at position 5意外的令牌 / 在 JSON 中的位置 5

It's not valid JSON, since the array elements aren't quoted.它不是有效的 JSON,因为没有引用数组元素。

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);

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:或编辑以创建有效的 JSON 字符串:

 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.或者确实使用@Barmar提供的match方法。

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']

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM