0

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

MatterGoal
  • 16,038
  • 19
  • 109
  • 186

3 Answers3

5

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"
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • I'd rather see an id being added than guessing that there is only one input element. :P – Shaz Feb 23 '11 at 18:34
  • @Shaz: indeed. I just hope the OP already querys for the element somehow. This is just for demonstration. – jAndy Feb 23 '11 at 18:35
3
>>> "user[2][city]".split(/[\[\]]+/)

Returns this array:

["user", "2", "city", ""]
broofa
  • 37,461
  • 11
  • 73
  • 73
  • problem with this is, if for some reason the first numeric value is empty, it would just split into `['user', 'city', '']`. – jAndy Feb 23 '11 at 18:48
1

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);
}
Humberto
  • 7,117
  • 4
  • 31
  • 46