当字符串'已经像数组一样编写时,将其解析为数组

Parse string into an array when it's already written like an array

本文关键字:数组 一样 字符串      更新时间:2023-09-26

我正在使用XMLHttpRequest读取文本文件。其内容为:

['01.html', '02.html', '03.html']

xhr.responseText是一个字符串,我不能将其强制转换为数组,即使它的书写方式与数组完全相同。

特别是,JSON.parse不能工作,因为这里的字符串使用单引号('...'),而JSON语法只识别带有双引号的字符串("...")。

只是以防您在JSON.parse上持久化。

你可以这样做。基本上,就像你说的,重新格式化字符串数组,用一组"双引号包围每个元素,然后解析它。

var test = "['01.html', '02.html', '03.html']".replace(/'/g, '"');
console.log(JSON.parse(test));