Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active May 23, 2024 13:49
Show Gist options
  • Save john-doherty/64b19691c44d895705f19413fa11ea20 to your computer and use it in GitHub Desktop.
Save john-doherty/64b19691c44d895705f19413fa11ea20 to your computer and use it in GitHub Desktop.
Convert a URL into a readable filename safe string
/**
* 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;
}
@toomim
Copy link

toomim commented May 23, 2024

This has a bug— the distinct urls foo!bar and foo/bar will both map to the same filename foo!bar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment