1

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.

1
  • I could split, loop and substr to check the patterns, but I'm hoping for something cleaner. Commented Feb 23, 2014 at 23:47

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Seems to work unless there are non-varaible splits, for instance: /user/:id/login/:name returns the id but the second value is undefined

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.