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

1

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

I'd rather see an id being added than guessing that there is only one input element. :P
@Shaz: indeed. I just hope the OP already querys for the element somehow. This is just for demonstration.
3
>>> "user[2][city]".split(/[\[\]]+/)

Returns this array:

["user", "2", "city", ""]

1 Comment

problem with this is, if for some reason the first numeric value is empty, it would just split into ['user', 'city', ''].
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.