Reputation: 1129
I have this code which works ok, but i was wondering if it could be done faster with jquery to get the index from input name attribute
<input name="inp[myindex]" value="bla" />
and the jquery
var $idx = $this.attr('name');
var $split = $idx.split('[');
$idx = $split[1];
$idx = $idx.replace(']', '');
Thanks in advance!
Upvotes: 3
Views: 3332
Reputation: 536429
A concise idiom to extract a string between two boundaries is split-pop-shift:
var subname= this.name.split('[').pop().split(']').shift();
or there's always the regex method, shorter still though ugly:
var subname= this.name.match(/\[([^[]*)\]/)[1];
jQuery is focused on DOM manipulations and doesn't have its own string processing functions to speak of. The method of using square brackets for indexed field names is a PHP quirk rather than anything inherent to HTML, which sees names only as plain old strings.
Upvotes: 7
Reputation: 78650
There are other ways to do this, but nothing with jquery. Just other variations of substring, replace, etc.
Upvotes: 0