Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "regexparam",
"version": "1.0.2",
"repository": "lukeed/regexparam",
"description": "A tiny (252B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍",
"description": "A tiny (236B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍",
"module": "dist/regexparam.mjs",
"main": "dist/regexparam.js",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# regexparam [![Build Status](https://travis-ci.org/lukeed/regexparam.svg?branch=master)](https://travis-ci.org/lukeed/regexparam)

> A tiny (252B) utility that converts route patterns into RegExp. Limited alternative to [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) 🙇
> A tiny (236B) utility that converts route patterns into RegExp. Limited alternative to [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) 🙇

With `regexparam`, you may turn a pathing string (eg, `/users/:id`) into a regular expression.

Expand Down
24 changes: 14 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
export default function (str) {
var c, o, tmp, keys=[], pattern='', arr=str.split('/');
arr[0] || arr.shift();
// This captures:
// 1. Leading slash, if any (unused... non-capturing group adds bytes).
// 2. Key type, if any.
// 3. Key name (or constant path component).
// 4. Optional flag.
var match, keys=[], pattern='', re=/(\/|^)([:*])?([^\/]*?)(\?)?(?=\/|$)/g;

while (tmp = arr.shift()) {
c = tmp[0];
if (c === '*') {
// An empty input string will match and not update `lastIndex`, leading to
// an infinite loop. The default to '/' avoids this.
while (match = re.exec(str || '/')) {
if (match[2] === '*') {
keys.push('wild');
pattern += '/(.*)';
} else if (c === ':') {
o = tmp[tmp.length - 1] === '?'; // optional?
keys.push( tmp.substring(1, o ? tmp.length - 1 : tmp.length) );
pattern += o ? '(?:/([^/]+?))?' : '/([^/]+?)';
} else if (match[2] === ':') {
keys.push( match[3] );
pattern += match[4] ? '(?:/([^/]+?))?' : '/([^/]+?)';
} else {
pattern += '/' + tmp;
pattern += '/' + match[3];
}
}

Expand Down