JavaScript / ECMAScript

URL Path Segment in JS

Match individual `/segment` parts of a URL path, capturing each one.

Try it in the JS tester →

Pattern

regexJS
\/([^\/?#\s]+)   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("\\/([^\\/?#\\s]+)", "g");
const input = "/users/42/posts?page=2";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

\/ matches the literal slash. ([^\/?#\s]+) captures one or more characters that aren't a slash, question mark, hash, or whitespace — i.e. one path segment. Useful for breaking apart a URL into its component pieces.

Examples

Input

/users/42/posts?page=2

Matches

  • /users
  • /42
  • /posts

Input

/api/v1/health

Matches

  • /api
  • /v1
  • /health

Input

no/path

No match

Same pattern, other engines

← Back to URL Path Segment overview (all engines)