将数组格式的字符串转换为javascript数组 [英] Convert string in array format to javascript array
本文介绍了将数组格式的字符串转换为javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,格式为:"['A', 'B', 'C']"
.我想将其转换为数组['A', 'B', 'C']
.我尝试使用JSON.parse()
,但是没有用.任何帮助将不胜感激.
I have a string in this format: "['A', 'B', 'C']"
. I want to convert it to an array ['A', 'B', 'C']
. I tried using JSON.parse()
but it did not work. Any help would be appreciated.
const strArray = "['A', 'B', 'C']";
const parsedString = JSON.parse(strArray);
console.log(parsedString);
推荐答案
通过将单引号替换为双引号并进行解析,将字符串转换为有效的json:
Convert the string to a valid json by replacing the single quotes with double quotes and parse:
const str = "['A', 'B', 'C']";
const result = JSON.parse(str.replace(/'/g, '"'));
console.log(result);
这篇关于将数组格式的字符串转换为javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文