I’ve been at this for hours, and I’m hitting a dead end. I’ve read up on Regular Expressions all over the place, but I’m still having trouble matching on anything more complex than basic patterns.
So, my problem is this:
I need to split an “&” delimited to string into a list of objects, but I need to account for the values containing the ampersand as well.
Please let me know if you can provide any help.
var subjectA = 'myTestKey=this is my test data & such&myOtherKey=this is the other value';
Update:
Alright, to begin with, thanks for the awesome, thoughtful responses. To give a little background on why I’m doing this, it’s to create a cookie utility in JavaScript that is a little more intelligent and supports keys ala ASP.
With that being said, I’m finding that the following RegExp /([^&=\s]+)=(([^&]*)(&[^&=\s]*)*)(&|$)/g does 99% of what I need it to. I changed the RegExp suggested by the contributors below to also ignore empty spaces. This allowed me to turn the string above into the following collection:
[
[myTestKey, this is my test data & such],
[myOtherKey, this is the other value]]
]
It even works in some more extreme examples, allowing me to turn a string like:
var subjectB = 'thisstuff===myv=alue me==& other things=&thatstuff=my other value too';
Into:
[
[thisstuff, ==myv=alue me==& other things=],
[thatstuff, my other value too]
]
However, when you take a string like:
var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';
Everything gets out of whack again. I understand why this is happening as a result of the regular expression above (kudos for a very awesome explanation), but I’m (obviously) not comfortable enough with regular expressions to figure out a work around.
As far as importance goes, I need this cookie utility to be able to read and write cookies that can be understood by ASP and ASP.NET & vice versa. From playing with the example above, I’m thinking that we’ve taken it as far as we can, but if I’m wrong, any additional input would be greatly appreciated.
tl;dr – Almost there, but is it possible to account for outliers like subjectC?
var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';
Actual ouput:
[
[me, ==regexs are hard for &me],
[you, ],
[you, nah, not really you\'re just a n00b]
]
Versus expected output:
[
[me, ==regexs are hard for &me&you=],
[you, nah, not really you\'re just a n00b]
]
Thanks again for all of your help. Also, I’m actually getting better with RegExp… Crazy.
If your keys cannot contain ampersands, then it’s possible:
Explanation:
This may not be the most efficient way to do this (because of the lookahead assertion that needs to be checked several times during each match), but it’s rather straightforward.