Reputation: 10153
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('='))
});
}
Upvotes: 1
Views: 40
Reputation: 1644
You can search for all instances of
(?:\?|&)([^\=]+)(?=\=)
by using the 'g' modifier.
Example:
https://regex101.com/r/mM4lR4/2
Upvotes: 1
Reputation: 700592
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));
Upvotes: 3
Reputation: 785621
You can use this array and grab captured group #1:
/[?&]([^=]+)/g
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"]
Upvotes: 1
Reputation: 19005
I'd do it this way:
var result = str.split("?")[1].split("&");
So if your string is 123?foo=bar&one=something¬hing=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]
.
Upvotes: 1