Reputation: 5210
I've seen a number of posts on matching/replacing a path like:
/login/:id/:name
However, I'm trying to figure out how I can return an array containing only the names of the params; id
, name
I've got the Regex down: /:[^\s/]+/g, "([\\w-]+)"
just struggling with the match.
Upvotes: 1
Views: 271
Reputation: 94101
You need to loop because match
won't grab capture groups in a global regex, so you'll end up having some extra character you don't need:
var url = '/login/:id/:name';
var res = [];
url.replace(/:(\w+)/g, function(_, match) {
res.push(match);
});
console.log(res); //=> ["id", "name"]
You can also use this helper:
String.prototype.gmatch = function(regex) {
var result = [];
this.replace(regex, function() {
var matches = [].slice.call(arguments, 1, -2);
result.push.apply(result, matches);
});
return result;
};
var res = url.gmatch(/:(\w+)/g); //=> ["id", "name"]
Upvotes: 1