简体   繁体   English

将字符串转换为Javascript中的数组?

[英]convert string to array in Javascript?

I have a string 我有一个弦

var str = '[SYSTEM, Test, check]'

I want to convert this String into array in order to access these values separately., like.. 我想将此String转换为数组,以便分别访问这些值。

var array = ['SYSTEM', 'Test', 'check'];

You can do that by removing the beginning and end brackets and then splitting the string by ', '. 您可以通过删除开头和结尾的括号,然后用','分隔字符串来实现。

var array = str.replace(/\[|\]/g,'').split(', ');

This uses a regex to remove the brackets and than the split method to make the array 这使用正则表达式删除括号,然后使用split方法制作数组

To elaborate a little more... I use /[|]/ to look for instances of [ and ]. 详细说明...我使用/ [|] /查找[和]的实例。 I flag the regex as global (the g) in order to find all instances of it. 我将正则表达式标记为全局(g)以查找其所有实例。 Then I replace the instances with an empty string. 然后,我用一个空字符串替换实例。 Once all the instances have been removed, I split the string into an array based off of a comma and space seperator ', ' 删除所有实例后,我根据逗号和空格分隔符','将字符串拆分为一个数组

UPDATE: 更新:

As per the comments, you should check for the brackets at the beginning and end of the string, since we will assume you want brackets from any other values. 根据注释,您应该检查字符串开头和结尾的方括号,因为我们假定您希望其他任何值都包含方括号。

var array = str.replace(/(^\[|\]$)/g, '').split(', ');
var array = str.substring(1, str.length - 1).split(", ");

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

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