path-to-regexp vs uri-js vs query-string vs url-template vs uri-template vs template-url
URL and URI Manipulation Libraries Comparison
1 Year
path-to-regexpuri-jsquery-stringurl-templateuri-templatetemplate-urlSimilar Packages:
What's URL and URI Manipulation Libraries?

URL and URI manipulation libraries in JavaScript provide developers with tools to parse, construct, and manipulate URLs (Uniform Resource Locators) and URIs (Uniform Resource Identifiers). These libraries simplify tasks such as encoding and decoding components, handling query strings, and working with different parts of a URL, making them essential for web applications that need to interact with APIs, handle routing, or manage links dynamically. They help ensure that URLs are properly formatted, encoded, and decoded, which is crucial for tasks like sending requests, creating links, and processing user input. These libraries often provide utilities for parsing query strings, handling path segments, and managing URL parameters, making them versatile tools for any web developer.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
path-to-regexp78,171,3118,44255.2 kB2110 months agoMIT
uri-js59,949,216313-305 years agoBSD-2-Clause
query-string14,312,9856,87153 kB28a month agoMIT
url-template4,962,0861877.99 kB12 years agoBSD-3-Clause
uri-template128,09142-14 years agoMIT
template-url65,2612-1410 years agoISC
Feature Comparison: path-to-regexp vs uri-js vs query-string vs url-template vs uri-template vs template-url

Path Matching and Parameter Extraction

  • path-to-regexp:

    path-to-regexp excels at converting path patterns into regular expressions, allowing for precise matching and extraction of parameters from URLs. It supports dynamic segments, optional parameters, and wildcard matching, making it highly versatile for routing and URL handling.

  • uri-js:

    uri-js provides comprehensive URI parsing and manipulation, including support for extracting components from URIs. However, it is not specialized in path matching or parameter extraction from URLs.

  • query-string:

    query-string focuses on query strings rather than path matching. It does not extract parameters from paths but provides utilities for parsing and stringifying query parameters, making it complementary to path matching libraries.

  • url-template:

    url-template supports parameter extraction and substitution within URL templates, but it is not designed for general path matching. It focuses on variable substitution within predefined templates.

  • uri-template:

    uri-template is designed to work with URI templates, allowing for parameter extraction based on template definitions. It supports both expanding and contracting URIs, making it useful for dynamic URL generation.

  • template-url:

    template-url does not handle path matching or parameter extraction. Instead, it focuses on generating URLs from templates with predefined structures, allowing for dynamic insertion of values into the URL.

Query String Manipulation

  • path-to-regexp:

    path-to-regexp does not handle query strings or their manipulation. It is focused on path matching and does not provide any utilities for working with query parameters.

  • uri-js:

    uri-js offers basic query string parsing and manipulation as part of its comprehensive URI handling capabilities. However, it is not specialized in query string manipulation like query-string and does not provide dedicated utilities for it.

  • query-string:

    query-string is specifically designed for query string manipulation. It provides functions for parsing query strings into objects, stringifying objects into query strings, and handling nested and array values, making it the go-to choice for query parameter handling.

  • url-template:

    url-template does not provide query string manipulation features. It is focused on variable substitution within URL templates and does not interact with query parameters.

  • uri-template:

    uri-template does not handle query string manipulation. It focuses on working with URI templates and does not provide any functionality for parsing or modifying query strings.

  • template-url:

    template-url does not provide any functionality for query string manipulation. It is focused on generating URLs from templates and does not interact with query parameters.

URI Template Support

  • path-to-regexp:

    path-to-regexp does not support URI templates. It is focused on path matching and parameter extraction using regular expressions and does not provide any functionality for working with URI templates.

  • uri-js:

    uri-js provides basic support for URI templates as part of its comprehensive URI handling capabilities. However, it is not specialized in URI templates and does not provide dedicated functionality for their processing.

  • query-string:

    query-string does not support URI templates. It is focused on parsing and manipulating query strings and does not provide any features related to URI templates or their processing.

  • url-template:

    url-template provides support for URI templates with a focus on variable substitution. It allows for simple template processing and variable replacement, but it is not as feature-rich as uri-template in terms of URI template specifications.

  • uri-template:

    uri-template is specifically designed for working with URI templates as defined by RFC 6570. It provides full support for expanding and contracting URIs based on template definitions, making it the go-to choice for URI template handling.

  • template-url:

    template-url supports URI templates in a limited way by allowing dynamic insertion of values into predefined URL structures. However, it does not provide full support for URI templates or their expansion/contraction.

Size and Performance

  • path-to-regexp:

    path-to-regexp is a lightweight library with a small footprint, making it efficient for performance-sensitive applications. Its focus on path matching and parameter extraction is implemented with minimal overhead, ensuring fast execution.

  • uri-js:

    uri-js is a more comprehensive library with a larger footprint due to its extensive URI parsing and manipulation capabilities. While it is well-optimized, its size may be a consideration for projects where bundle size is a critical factor.

  • query-string:

    query-string is also a lightweight library designed for efficient query string manipulation. It is optimized for performance, with fast parsing and stringifying functions that handle query parameters with minimal resource usage.

  • url-template:

    url-template is a small library that provides lightweight URI template functionality. Its focus on simple variable substitution keeps it efficient, making it suitable for applications that require quick and easy template processing without significant overhead.

  • uri-template:

    uri-template is a lightweight library focused on URI template processing. It is designed to be efficient in expanding and contracting URIs based on templates, with minimal impact on performance.

  • template-url:

    template-url is a lightweight library for generating URLs from templates. Its simplicity and focus on template-based URL generation result in low overhead and fast performance, making it suitable for applications where efficiency is important.

Ease of Use: Code Examples

  • path-to-regexp:

    Path Matching Example with path-to-regexp

    import { pathToRegexp, match } from 'path-to-regexp';
    
    // Define a path pattern
    const pattern = '/users/:id';
    
    // Convert the pattern to a regex
    const regex = pathToRegexp(pattern);
    
    // Match a URL against the regex
    const url = '/users/123';
    const isMatch = regex.test(url);
    
    // Extract parameters
    const matchResult = match(pattern);
    const params = matchResult('/users/123');
    
    console.log(isMatch); // true
    console.log(params); // { path: '/users/123', index: 0, params: { id: '123' } }
    
  • uri-js:

    URI Parsing Example with uri-js

    import { URI } from 'uri-js';
    
    // Parse a URI
    const uri = URI.parse('https://example.com:8080/path?query=123#fragment');
    
    // Construct a URI
    const constructedUri = URI.serialize({ scheme: 'https', host: 'example.com', path: '/path' });
    
    console.log(uri);
    console.log(constructedUri);
    
  • query-string:

    Query String Manipulation Example with query-string

    import { parse, stringify } from 'query-string';
    
    // Parse a query string into an object
    const queryString = '?name=John&age=30&hobbies=reading,traveling';
    const parsed = parse(queryString);
    
    // Stringify an object into a query string
    const obj = { name: 'Jane', age: 25, hobbies: ['music', 'sports'] };
    const stringified = stringify(obj);
    
    console.log(parsed); // { name: 'John', age: '30', hobbies: 'reading,traveling' }
    console.log(stringified); // ?name=Jane&age=25&hobbies=music,sports
    
  • url-template:

    URL Template Example with url-template

    import { parse, compile } from 'url-template';
    
    // Define a URL template
    const template = compile('https://example.com/users/{id}/posts/{postId}');
    
    // Generate a URL with values
    const url = template.expand({ id: 123, postId: 456 });
    
    console.log(url); // https://example.com/users/123/posts/456
    
  • uri-template:

    URI Template Example with uri-template

    import { UriTemplate } from 'uri-template';
    
    // Define a URI template
    const template = new UriTemplate('https://example.com/users/{id}/posts/{postId}');
    
    // Expand the template with values
    const expandedUri = template.expand({ id: 123, postId: 456 });
    
    console.log(expandedUri); // https://example.com/users/123/posts/456
    
  • template-url:

    URL Generation Example with template-url

    import { templateUrl } from 'template-url';
    
    // Define a URL template
    const urlTemplate = 'https://example.com/users/{id}/posts/{postId}';
    
    // Generate a URL with dynamic values
    const url = templateUrl(urlTemplate, { id: 123, postId: 456 });
    
    console.log(url); // https://example.com/users/123/posts/456
    
How to Choose: path-to-regexp vs uri-js vs query-string vs url-template vs uri-template vs template-url
  • path-to-regexp:

    Choose path-to-regexp if you need a lightweight and efficient solution for converting paths into regular expressions, especially for routing in web applications. It is ideal for projects that require precise control over path matching and parameter extraction.

  • uri-js:

    Choose uri-js if you need a comprehensive library for parsing, constructing, and validating URIs. It is suitable for applications that require detailed URI manipulation, including support for various URI schemes, percent-encoding, and validation according to RFC standards.

  • query-string:

    Choose query-string if you need a simple and efficient library for parsing and stringifying query strings. It is particularly useful for handling URL parameters in a clean and straightforward manner, making it a great choice for projects that require easy manipulation of query data.

  • url-template:

    Choose url-template if you need a lightweight implementation of URI templates that supports variable substitution. It is a good choice for projects that require a simple and efficient way to generate URLs from templates without the overhead of a larger library.

  • uri-template:

    Choose uri-template if you need to work with URI templates as defined by RFC 6570. This library is useful for applications that need to expand or contract URIs based on templates, making it ideal for scenarios involving dynamic URL generation and API integration.

  • template-url:

    Choose template-url if you need to create URLs from templates with dynamic parameters. This package is useful for applications that require generating URLs based on a predefined structure, allowing for easy insertion of variable values into the URL.

README for path-to-regexp

Path-to-RegExp

Turn a path string such as /user/:name into a regular expression.

NPM version NPM downloads Build status Build coverage License

Installation

npm install path-to-regexp --save

Usage

const {
  match,
  pathToRegexp,
  compile,
  parse,
  stringify,
} = require("path-to-regexp");

Parameters

Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name").

const fn = match("/:foo/:bar");

fn("/test/route");
//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }

Wildcard

Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo).

const fn = match("/*splat");

fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }

Optional

Braces can be used to define parts of the path that are optional.

const fn = match("/users{/:id}/delete");

fn("/users/delete");
//=> { path: '/users/delete', params: {} }

fn("/users/123/delete");
//=> { path: '/users/123/delete', params: { id: '123' } }

Match

The match function returns a function for matching strings against a path:

  • path String or array of strings.
  • options (optional) (Extends pathToRegexp options)
    • decode Function for decoding strings to params, or false to disable all processing. (default: decodeURIComponent)
const fn = match("/foo/:bar");

Please note: path-to-regexp is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).

PathToRegexp

The pathToRegexp function returns a regular expression for matching strings against paths. It

  • path String or array of strings.
  • options (optional) (See parse for more options)
    • sensitive Regexp will be case sensitive. (default: false)
    • end Validate the match reaches the end of the string. (default: true)
    • delimiter The default delimiter for segments, e.g. [^/] for :named parameters. (default: '/')
    • trailing Allows optional trailing delimiter to match. (default: true)
const { regexp, keys } = pathToRegexp("/foo/:bar");

Compile ("Reverse" Path-To-RegExp)

The compile function will return a function for transforming parameters into a valid path:

  • path A string.
  • options (See parse for more options)
    • delimiter The default delimiter for segments, e.g. [^/] for :named parameters. (default: '/')
    • encode Function for encoding input strings for output into the path, or false to disable entirely. (default: encodeURIComponent)
const toPath = compile("/user/:id");

toPath({ id: "name" }); //=> "/user/name"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"

const toPathRepeated = compile("/*segment");

toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"

// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
const toPathRaw = compile("/user/:id", { encode: false });

toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"

Stringify

Transform TokenData (a sequence of tokens) back into a Path-to-RegExp string.

  • data A TokenData instance
const data = new TokenData([
  { type: "text", value: "/" },
  { type: "param", name: "foo" },
]);

const path = stringify(data); //=> "/:foo"

Developers

  • If you are rewriting paths with match and compile, consider using encode: false and decode: false to keep raw paths passed around.
  • To ensure matches work on paths containing characters usually encoded, such as emoji, consider using encodeurl for encodePath.

Parse

The parse function accepts a string and returns TokenData, the set of tokens and other metadata parsed from the input string. TokenData is can used with match and compile.

  • path A string.
  • options (optional)
    • encodePath A function for encoding input strings. (default: x => x, recommended: encodeurl)

Tokens

TokenData is a sequence of tokens, currently of types text, parameter, wildcard, or group.

Custom path

In some applications, you may not be able to use the path-to-regexp syntax, but still want to use this library for match and compile. For example:

import { TokenData, match } from "path-to-regexp";

const tokens = [
  { type: "text", value: "/" },
  { type: "parameter", name: "foo" },
];
const path = new TokenData(tokens);
const fn = match(path);

fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } }

Errors

An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.

Unexpected ? or +

In past releases, ?, *, and + were used to denote optional or repeating parameters. As an alternative, try these:

  • For optional (?), use an empty segment in a group such as /:file{.:ext}.
  • For repeating (+), only wildcard matching is supported, such as /*path.
  • For optional repeating (*), use a group and a wildcard parameter such as /files{/*path}.

Unexpected (, ), [, ], etc.

Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To use these characters literally, escape them with a backslash, e.g. "\\(".

Missing parameter name

Parameter names must be provided after : or *, and they must be a valid JavaScript identifier. If you want an parameter name that isn't a JavaScript identifier, such as starting with a number, you can wrap the name in quotes like :"my-name".

Unterminated quote

Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character.

Express <= 4.x

Path-To-RegExp breaks compatibility with Express <= 4.x in the following ways:

  • The wildcard * must have a name, matching the behavior of parameters :.
  • The optional character ? is no longer supported, use braces instead: /:file{.:ext}.
  • Regexp characters are not supported.
  • Some characters have been reserved to avoid confusion during upgrade (()[]?+!).
  • Parameter names now support valid JavaScript identifiers, or quoted like :"this".

License

MIT