Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on [] brackets

the string is the name of some input fields. Examples:

a[b][c]

x[y][z][]

I'm trying to produce multidimensional arrays from it.

a.b.c = value

x.y.z = [value] (value is an array because of [])

anyway i have some ideas on how to do that but first I need to split the string into an array that contains all keys and subkeys.

Searching google I've come up with this

var parts = inputName.match(/[^\[\]]+/g);

it gets me [a,b,c], but on the 2nd example I get [x,y,z] instead of [x,y,z, null]

Any way I can also match [] and add it to the list as null ? I'm not that familiar with regular expressions


@AnnaK. Why can't you simply use ids and keys to send your information? Is it a form that is dynamic in its size? Is it because you're developing a framework that needs to be dynamic? Is it because you're using a function multiple places? Can't you serialize it by using the names? We can't give you suggestions because we still don't know why you need to transfer it as an array (which would be serialized anyway), and we still don't know what your form looks like

Because I'm trying to send the form data with Ajax. Also, before I send the data, I need to prepend a few fields that I create with javascript. I cannot serialize it, at least not with jQuery.serializeArray if that's what you meant, because if I have multiple keys like x[y][z][], only the last one will appear

like image 770
Anna K. Avatar asked Nov 25 '13 16:11

Anna K.


2 Answers

You can use the following solution:

var parts = inputName.split(/[[\]]{1,2}/);
parts.length--; // the last entry is dummy, need to take it out

console.log(parts); // ["x", "y", "z", ""] 

If you need the null value (because there is processing you have no control over for example) you can use this snippet to update the result (curtesy of @Ties):

parts = parts.map(function(item){ return item === '' ? null : item });
like image 76
Tibos Avatar answered Sep 18 '22 02:09

Tibos


Basic idea I had was to look for a [] and than use map() to replace it with null.

("a[bb][c][]").match(/([^[\]]+|\[\])/g).map( function(val) { return val==="[]" ? null : val; });
like image 43
epascarello Avatar answered Sep 19 '22 02:09

epascarello