I am trying to parse url-encoded strings that are made up of key=value pairs separated by either &
or &
.
The following will only match the first occurrence, breaking apart the keys and values into separate result elements:
var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/)
The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:
['1111342', 'Adam%20Franco']
Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values:
var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/g)
The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:
['1111342=Adam%20Franco', '&348572=Bob%20Jones']
While I could split the string on &
and break apart each key/value pair individually, is there any way using JavaScript's regular expression support to match multiple occurrences of the pattern /(?:&|&)?([^=]+)=([^&]+)/
similar to PHP's preg_match_all()
function?
I'm aiming for some way to get results with the sub-matches separated like:
[['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']]
or
[['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']]
If you can get away with using
map
this is a four-line-solution:Ain't pretty, ain't efficient, but at least it is compact. ;)
Well... I had a similar problem... I want an incremental / step search with RegExp (eg: start search... do some processing... continue search until last match)
After lots of internet search... like always (this is turning an habit now) I end up in StackOverflow and found the answer...
Whats is not referred and matters to mention is "
lastIndex
" I now understand why the RegExp object implements the "lastIndex
" propertySplitting it looks like the best option in to me:
I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually:
result
is an object:The regex breaks down as follows:
If someone (like me) needs Tomalak's method with array support (ie. multiple select), here it is:
input
?my=1&my=2&my=things
result
1,2,things
(earlier returned only: things)Use
window.URL
: