Last active
May 23, 2024 13:49
-
-
Save john-doherty/64b19691c44d895705f19413fa11ea20 to your computer and use it in GitHub Desktop.
Convert a URL into a readable filename safe string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert a URL into a readable filename safe string | |
* - sort query params | |
* - remove protocol | |
* - replace / with ! | |
* - replace ? with !! | |
* - replace remaining illegal characters with - | |
* @example | |
* INPUT: convertUrlToReadableFilename('https://orcascan.com/guides/how-to-scan-barcodes-into-microsoft-excel-59fd67f9'); | |
* OUTPUT: 'orcascan.com!guides!how-to-scan-barcodes-into-microsoft-excel-59fd67f9' | |
* @param {string} url - url to convert | |
* @returns {string} filename safe string | |
*/ | |
function convertUrlToReadableFilename(url) { | |
// sort query params to improve consistency | |
var parts = url.split('?'); | |
var baseUrl = parts[0]; | |
var sortedQuery = parts?.[1]?.split('&')?.sort()?.join('&') || ''; | |
var sortedUrl = [baseUrl, sortedQuery].filter(Boolean).join('?'); | |
// replace illegal characters | |
var filename = sortedUrl; | |
filename = filename.replace(/(^\w+:|^)\/\//, ''); // remove protocol | |
filename = filename.replace(/[/]/g, '!'); // replace / with ! | |
filename = filename.replace(/[\\?]/g, '!!'); // replace ? with !! | |
filename = filename.replace(/[%*:|"<>]/g, '-'); // replace everything else with - | |
return filename; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has a bug— the distinct urls
foo!bar
andfoo/bar
will both map to the same filenamefoo!bar
.