简体   繁体   English

如何将字符串解析为数组

[英]How to parse a string into an array

If a have a string in this format: 如果一个具有以下格式的字符串:

$parsethis = 'string[1][2]';

How do I parse it so my result is an array like: 我如何解析它,所以我的结果是一个像这样的数组:

$parsed = ['string', 1 , 2]

You can do something like this: 您可以执行以下操作:

var $parsethis = 'string[1][2]';
var arr = $parsethis.replace(/\]/g,'').split('['); 
//arr = ["string", "1", "2"]
alert(arr); //alerts "string,1,2"

The arr array will be all strings, though. 不过, arr数组将是所有字符串。 Based on the question, I do not know how you will be using the results. 基于该问题,我不知道您将如何使用结果。

You can get an array from that string using str.split(), and then cleaning it up with str.replace(). 您可以使用str.split()从该字符串中获取一个数组,然后使用str.replace()对其进行清理。

var parsed = parsethis.split('['); 
console.log(parsed); // ["string", "1]", "2]"]
for(var i = 0; i++; i<parsed.length){
  parsed[i] = parsed[i].replace(']','');
}
console.log(parsed); // ["string", "1", "2"]

I think REGEX is the way to go here, in compiination with the Arrays split method. 我认为REGEX是与Arrays split方法配合使用的方法。

var array = $parsed.split(/\]\[|\[|\]/);

console.log(array) results in
Array [ "string", "1", "2", "" ]

iam not very good at using regular expressions, but maybe this is leading you in the right direction. 我不太擅长使用正则表达式,但这也许会引导您朝着正确的方向发展。

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

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