I have some input text field in a form that have name with this format: sometext[234][sometext]
Something like <input type="text" name="user[2][city]" />
I need obtain 'user','2' and 'city' with split function.
Thank you
I have some input text field in a form that have name with this format: sometext[234][sometext]
Something like <input type="text" name="user[2][city]" />
I need obtain 'user','2' and 'city' with split function.
Thank you
I guess a regular expression fits better here.
var res = document.getElementsByTagName('input')[0].getAttribute('name').match(/^(\w+)?\[(\d+)?\]\[(\w+)?\]$/);
console.log(res[1]); // === "user"
console.log(res[2]); // === "2"
console.log(res[3]); // === "city"
>>> "user[2][city]".split(/[\[\]]+/)
Returns this array:
["user", "2", "city", ""]
Have you used regexes? Try this sample (available in jsFiddle):
var re = /(.+?)\[(\d+)\]\[(.+?)\]/;
var result = re.exec("user[2][city]");
if (result != null)
{
var firstString = result[1]; // will contain "user"
var secondString = result[2]; // will contain "2"
var thirdString = result[3]; // will contain "city"
alert(firstString + "\n" + secondString + "\n" + thirdString);
}