Jump to content

string dot notation to brackets


Recommended Posts

I have a string e.g.




and I want to change the string to;




I have come up with some code that works but is a bit of a hack, my code is below;

var array = field.split(".");
field = array[0]+'['+array[1]+']['+array[2]+']';

Is there a better way, I am sure there is using regex?




Edited by ale1981
Link to comment
Share on other sites

Your question is not clear are you wanting convert the string 'products.0.name' to the string 'products[0][name]' or are wanting to convert it to array notation so you can return the name item from the array at index 0 of the variable named products?


sorry, yes, i would like the string 'products.0.name' converted to string 'products[0][name]'

Link to comment
Share on other sites


Your way words just fine. The other way would be to use regex

field = field.replace(/(\w+)\.(\d+)\.(\w+)/g, '$1[$2][$3]');


Thanks, I knew there would be a regex way, I am just useless when it comes to regex!
I am guessing the .replace is quicker as it is done with one function?
Edited by ale1981
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.