Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?
    text
    copied!<p>I am trying to parse url-encoded strings that are made up of key=value pairs separated by either <code>&amp;</code> or <code>&amp;amp;</code>. </p> <p>The following will only match the first occurrence, breaking apart the keys and values into separate result elements:</p> <pre><code>var result = mystring.match(/(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/) </code></pre> <p>The results for the string '1111342=Adam%20Franco&amp;348572=Bob%20Jones' would be:</p> <pre><code>['1111342', 'Adam%20Franco'] </code></pre> <p>Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values:</p> <pre><code>var result = mystring.match(/(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/g) </code></pre> <p>The results for the string '1111342=Adam%20Franco&amp;348572=Bob%20Jones' would be:</p> <pre><code>['1111342=Adam%20Franco', '&amp;348572=Bob%20Jones'] </code></pre> <p>While I could split the string on <code>&amp;</code> 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 <code>/(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/</code> similar to PHP's <code>preg_match_all()</code> function?</p> <p>I'm aiming for some way to get results with the sub-matches separated like:</p> <pre><code>[['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']] </code></pre> <p>or </p> <pre><code>[['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload