novwhisky
novwhisky

Reputation: 485

RegEx to split query string with native JS

Where window.location.search is

?foo=myFoo&fooAndBar=myFoo%26Bar;bar=myBar

What regular expression would correctly split the string at its query separators? Note that ampersand (&) and semicolon (;) are both valid separators.

Sample use:

// slice() is used just to trim the leading "?"
window.location.search.slice(1).split(/ _WORKING_REGEX_ /);

>>> [object Array]:

    [0] => "foo=myFoo",
    [1] => "fooAndBar=myFoo&Bar",
    [2] => "bar=myBar"

I've found the correct match for ampersands, but not semicolons:

/&(?!\w+;)/

EDIT: T.J. Crowder pointed out that my error was in the original URL encoding of using & as an escaped ampersand where it would be correctly encoded instead as %26. Given that, the correct RegEx is much easier to match

window.location.search.slice(1).split(/[&;]/)

Here is the original test URL I posted before the correction for reference:

?foo=myFoo&fooAndBar=myFoo&Bar;bar=myBar

Upvotes: 0

Views: 627

Answers (2)

georg
georg

Reputation: 215009

this seems to work:

"?foo=myFoo&fooAndBar=myFoo&Bar;bar=myBar".match(/(&\w+;|[^&;])+/g)
> ["?foo=myFoo", "fooAndBar=myFoo&Bar", "bar=myBar"]

&\w+; to match entities is pretty naive, but you got the idea.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075079

Note that ampersand (&) and semicolon (;) are both valid separators.

So, um:

var pairs = queryString.split(/[;&]/);

?

Or, to deal with the potential ? at the beginning:

var pairs = queryString.replace(/^\??/, '').split(/[;&]/);

Upvotes: 1

Related Questions