kjdion84 kjdion84 - 1 year ago 75
Javascript Question

Check if an element has array name, and extract info

Lets say I have the following input:

<input type="text" name="action[5][3]">

How do I check to see if the input name is "action" considering it also includes keys? I.e.:

if (hasArrayName($(this).attr('name'), 'action') == true) {
console.log('element is an action');

Also, how do I extract each bit of information from the name? I want to map these 3 pieces of information out like so:

var array_name = 'action';
var index_1 = '5';
var index_2 = '3';

Any help would be greatly appreciated.

Answer Source

For finding a susbtring in a string use indexOf:

console.log( $(this).attr('name').indexOf('action') );

For finding parts of name you can use regexp and exec for example:

console.log( /(action)\[(\d+)\]\[(\d+)\]/.exec('action[2][5]') );
// ["action[2][5]", "action", "2", "5"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download