简体   繁体   English

JavaScript 将字符串转换为数组 Object

[英]JavaScript convert String into Array Object

How do I convert string to array object.如何将字符串转换为数组 object。

I have string我有字符串

let colors = "[red, blue, green]"让 colors = “[红,蓝,绿]”

and would like to convert as并想转换为

String[] colors = ["red", "blue", "green"]字符串[] colors = [“红”、“蓝”、“绿”]

Is there any inbuilt functions available for this conversion?是否有可用于此转换的内置函数?

Thank you for looking into it.谢谢你调查它。

I would follow @Jannes Carpentier 's approach - but to givae an alternative - you can use slice to get the text (non-brackets) portion of the string and then split on the " , " to get an array of the text items and then re-assign it to the original variable.我会遵循@Jannes Carpentier 的方法-但要提供替代方法-您可以使用 slice 获取字符串的文本(非括号)部分,然后在 " , " 上拆分以获取文本项数组和然后将其重新分配给原始变量。

 let colors = "[red, blue, green]" colors = colors.slice(1,-1).split(', '); console.log(colors); // gives ["red", "blue", "green"]

First remove the brackets首先去掉括号

Then split on ", "然后拆分", "

 let colors = "[red, blue, green]" colors = colors.replace(/([\[\]])/g, ""); colors = colors.split(", "); console.log(colors);

Instead of replacing all [ ] you could also remove the first and last character from the string除了替换所有[ ]您还可以从字符串中删除第一个和最后一个字符

And then split on ", "然后拆分", "

 let colors = "[red, blue, green]" colors = colors.substring(1, colors.length - 1); colors = colors.split(", "); console.log(colors);

If your data isn't formatted in any common standard, you are unlikely to find a prebuilt data parser.如果您的数据没有按照任何通用标准进行格式化,那么您不太可能找到预构建的数据解析器。 If you have control over the input string, it would be better to format it as a json string as follows: '["red", "green", "blue"]' Then you can easily take it apart with JSON.parse().如果您可以控制输入字符串,最好将其格式化为 json 字符串,如下所示:'["red", "green", "blue"]' 然后您可以使用 JSON.parse( )。

The other two answers have very satisfactory parsers for your data, however, I prefer not to count on the existence of whitespace in my input.其他两个答案对您的数据有非常令人满意的解析器,但是,我不想指望输入中是否存在空格。 A parser such as解析器如

function customParse(data) {
  return data
    .substring(1, data.length -1)
    .split(",", data)
    .map(trim);
}

console.log(customParse("[red, blue,green]"));

will work regardless of whitespace.无论空格如何,都可以使用。

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

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