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. 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().
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.