Skip to content

Commit

Permalink
Add preferJsRegexpLookbehind option (sindresorhus#105)
Browse files Browse the repository at this point in the history
  • Loading branch information
loynoir committed Aug 7, 2021
1 parent 3fb24bb commit 1228663
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 7 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ export interface Options {
```
*/
readonly sortQueryParameters?: boolean;

/**
prefer js-regexp-lookbehind{@link https://caniuse.com/js-regexp-lookbehind}
@default true
*/
readonly preferJsRegexpLookbehind?: boolean;
}

/**
Expand Down
24 changes: 23 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export default function normalizeUrl(urlString, options) {
removeSingleSlash: true,
removeDirectoryIndex: false,
sortQueryParameters: true,
// ref: https://caniuse.com/js-regexp-lookbehind
preferJsRegexpLookbehind: true,
...options,
};

Expand Down Expand Up @@ -121,7 +123,27 @@ export default function normalizeUrl(urlString, options) {

// Remove duplicate slashes if not preceded by a protocol
if (urlObject.pathname) {
urlObject.pathname = urlObject.pathname.replace(/(?<!\b[a-z][a-z\d+\-.]{1,50}:)\/{2,}/g, '/');
if (options.preferJsRegexpLookbehind) {
urlObject.pathname = urlObject.pathname.replace(
// prevent SyntaxError which can not be try-catch
new RegExp(
// generated from /(?<!\b[a-z][a-z\d+\-.]{1,50}:)\/{2,}/g
"/(?<!\\b[a-z][a-z\\d+\\-.]{1,50}:)\\/{2,}/g"
),
'/'
);
} else {
// ref: https://github.com/sindresorhus/normalize-url/blob/454970b662086e8856d1af074c7a57df96545b8b/index.js#L136
// TODO: Use the following instead when targeting Node.js 10
// `urlObj.pathname = urlObj.pathname.replace(/(?<!https?:)\/{2,}/g, '/');`
urlObject.pathname = urlObject.pathname.replace(/((?!:).|^)\/{2,}/g, (_, p1) => {
if (/^(?!\/)/g.test(p1)) {
return `${p1}/`;
}

return '/';
});
}
}

// Decode URI octets
Expand Down

0 comments on commit 1228663

Please sign in to comment.