Javascript RegEx for parsing search parameters

This is my first question posed on the stack, because really, I just can't wrap my brain around a regex. I am trying to build an advanced search for directories in a university library so that after a patron has searched for, say, "football" in several different categories of materials, by clicking the "change my search" button, he returns them to the form with all their previous searches remembered ... It's an old, proprietary system, so by default it returns the patron to the search form but forces them to start from scratch.

The location bar still has all the parameters, so I want to make this regex and fill the form using JS. This is what the line looks like:

/search~S13/X?NOSRCH=(football)&m=i&m=g&m=r&m=r&m=1&m=5&m=g&m=o&m=7&m=j&m=i&m=2&m=3&m=q&m=m&SORT=D&SUBKEY=(football)

I want to capture the value of m, which can happen much more often than in the above example. So far I am doing this:

var str = location.search.match(/m.*?&/g);

      

which returns

"m=i&", "m=g&", "m=r&", "m=r&", "m=1&", "m=5&", "m=g&", "m=o&", "m=7&", "m=j&", "m=i&", "m=2&", "m=3&", "m=q&", "m=m&"

      

How would you go about using the value i

in m=i&

?

+3


source to share


4 answers


I may have misunderstood your question, but I don't think RegEx is necessary if you are using JavaScript.

Anyway, first find the search part of the string and cut the question mark from the beginning, for example

var str = window.location.search.slice(1);

      

Then you can either traverse the RegEx route or a simple JavaScript route.

REGEX:

Create a template using a capture and capture group (in parentheses):

var regexPttrn = /(?:m\=)([^&=]+)/ig;

      

The first group uses ?:

symbols to search m=

. Once it has found them, it captures any group of consecutive characters that are not ampersands or equal signs.

Unfortunately, you need to use a method exec

inside the loop to do this , because it exec

only performs one match at a time, and you need to check that the returned array has the property you need before using it, etc.

JAVASCRIPT:

Better yet, instead of using RegEx, split str

as defined above into an array of different properties using an ampersand as a delimiter:



var arr = str.split('&');

      

So this will create an array of strings, for example "m=i"

, "m=g"

etc.

Then split each one into key-value pairs by running a loop and dividing each element arr

by an equal sign as a separator:

var pairs = [];
for (var i = 0; i < arr.length; i += 1) {
    pairs[i] = arr[i].split("=");
}

      

Thus, you will get an array containing several small arrays that structurally look like this:

[
    [ "NOSRCH", "FOOTBALL" ],
    [ "m", "i" ],
    [ "m", "g" ],
    /* and so on, until... */
    [ "EY", "(football)" ]
]

      

To get just the value m

, you can modify the above loop to create an array of just such values:

var pairs = [],
    m_results = [];
for (var i = 0; i < arr.length; i += 1) {
    pairs.push(arr[i].split("="));
    if (pairs[i][0] === "m") {
        m_results.push(pairs[i][1]);
    }
}

      

The array m_results

will then contain all the values ​​associated with m

in your search string.

Only 10 lines of code and much easier to comment out, debug, and reuse than trying to torture the RegEx pattern, I think, though I see, RegEx will be more concise if you can get it to capture effectively.

+1


source


I can show you how you can iterate over a string; you probably know JavaScript better than I do, so you know how to make an array from these results:

var myregexp = /\bm=([^&]*)/g;
var match = myregexp.exec(subject);
while (match != null) {
    // matched text: match[1], add that to your result array
    }
    match = myregexp.exec(subject);
}

      

Explanation of regex:



\b      # Start at the beginning of an alphanumeric "word"
m=      # (in this case, it just one letter) "m", followed by "="
(       # Match and capture in group number 1:
 [^&]*  #  any number of characters except ampersands
)       # End of capturing group.

      

As far as I know, there is no direct way to populate an array containing only the matches from the capturing group, not the whole regex matches.

+1


source


Since this is from location.search

, you can do this:

location.search.substring(1).split('&').filter(function (e) {
    return /^m=/.test(e);
}).map(function (e) {
    return e.substring(2); 
});

      

The first substring

is to remove ?

from the query string in location.search

.

+1


source


var s = '/search~S13/X?NOSRCH=(football)&m=i&m=g&m=r&m=r&m=1&m=5&m=g&m=o&m=7&m=j&m=i&m=2&m=3&m=q&m=m&SORT=D&SUBKEY=(football)';
s.split(/&/).map(function(x) {
  return x.split(/=/);
}).filter(function(x) {
  return x[1] == 'i';
}); // => [['m', 'i'], ['m', 'i']]

      

0


source







All Articles