0

I've got the following code to get the value of input name array key with javascript:

var input = document.querySelector('input');
var value = input.name.match(/\[(.*?)\]/)[1];

console.log(value);
<input type="text" name="hello[101][]" />

Now this works fine.

But I am wondering if there is a better way then ...name.match(/\[(.*?)\]/)[1]; to get the input name array key value(s)? Like is there a way to convert the hello[101][] string to a kind of javascript array or object? Like what if I want to get all keys from:

<input type="text" name="hello['one'][101]['test'][]" />
3
  • I probably wouldn't follow this pattern myself - but you could use eval() to process that string as code Commented Mar 4, 2017 at 17:32
  • @hackerrdave thanks for your comment, am I doing something wrong with eval()? doesn't shows anything jsfiddle.net/yv4ceffr input.name is a string though Commented Mar 4, 2017 at 17:36
  • I suggest using ids instead of names to reference the elements on the client side, and format the ids in such a way that they are easy to work with. Names are really for the server (IMHO). Commented Mar 4, 2017 at 18:17

2 Answers 2

2

Here is an eval example

var str = "hello['one'][101]['test'][]", 
  parts=eval(str.substring(str.indexOf("[")).split("][").join(","))
console.log(parts)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @mplungjan! Much appreciated, will accept in the near future if no better answer occurs!
1

You can pass a regular expression to split() method to make an array for you. It can be done pretty much the same way.

var arrayOfIntputValues = input.name.split(/\[(.*?)\]/)

But it will return ["hello", "'one'", "", "101", "", "'test'", "", "", ""] so you have to delete empty elements.

arrayOfInputVaules.filter(function(x){return x!=''})

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.