1

Given the following two examples:

'123?type=hand' ===> 'type'

'123?type=hand&status=alive' ===> 'type status'

In english I want: Find the ? and remove everything in front. Find = and remove everything after it until the &.

In the end of the day what I want is just either a string, array, whatever of the actual queryStringVariableNames. Not any of the values.

I think I'm over complexifying it. :)

Here is a couple snippets I have been working with:

var pattern = /\*(\?)|\*(\&)|(\=)\*/ig;
var pattern = /(.+?\?)/g;

str.replace(pattern, function (matcher, positionOfMatch, item) {
            return '';
});

I started using the longform of replace so I could see better what was going on.

EDIT

My exact implementation ended up being the following:

function (str) {
  str = str.substr(str.indexOf('?') + 1);

  return str.split('&')
            .map(function (i) {
               return i.substr(0, i.indexOf('='))
            });
}

4 Answers 4

3

It would be easier to just use string operations instead of regular expressions. This gives you an array with the keys in the string:

var str = '123?type=hand&status=alive';

str = str.substr(str.indexOf('?') + 1);
var keys = str.split('&');
for (var i = 0; i < keys.length; i++) {
  keys[i] = keys[i].substr(0, keys[i].indexOf('='));
}

// Show in StackOverflow snippet
document.write(JSON.stringify(keys));

Sign up to request clarification or add additional context in comments.

Comments

1

I'd do it this way:

var result = str.split("?")[1].split("&");

So if your string is 123?foo=bar&one=something&nothing=else, you're getting an array of strings as a result: foo=bar, one=something, nothing=else.

Then the first parameter is accessible by result[0], its key is accessible with result[0].split("=")[0] and its value is accessible with result[0].split("=")[1].

Comments

1

You can use this array and grab captured group #1:

/[?&]([^=]+)/g

RegEx Demo

Code:

var str = '123?type=hand&status=alive';
var re = /[?&]([^=]+)/g; 
var m;
var result = [];

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex)
        re.lastIndex++;
    result.push(m[1]);
}

console.log(result);
//=> ["type", "status"]

Comments

1

You can search for all instances of

(?:\?|&)([^\=]+)(?=\=)

by using the 'g' modifier.

Example:

https://regex101.com/r/mM4lR4/2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.