Skip to content

Instantly share code, notes, and snippets.

@ppeelman
Created April 12, 2023 09:46
Show Gist options
  • Save ppeelman/62518c680c9c4a4c3ff4aca438c35677 to your computer and use it in GitHub Desktop.
Save ppeelman/62518c680c9c4a4c3ff4aca438c35677 to your computer and use it in GitHub Desktop.
export const firstLetter = (str: string): string => str[0];
export const toUppercase = (str: string): string => str.toUpperCase();
export const toLowercase = (str: string): string => str.toLowerCase();
export const trim = (str: string) => str.trim();
// https://stackoverflow.com/a/5717133/11351782
export function isValidUrl(str: string): boolean {
const pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return pattern.test(str);
}
export const capitalize = (str: string): string => str[0].toUpperCase() + str.slice(1, str.length).toLowerCase()
export const abbreviateUrl = (urlStr: string): string => {
try {
const {protocol, hostname, port, pathname, searchParams} = new URL(urlStr);
if (urlStr.length > 40) {
const portStr = port ? `:${port}` : '';
const lastPartOfPath = last(pathname.split('/'));
const searchParamsStr = searchParams.toString().length > 0 ? `?${searchParams.toString()}` : '';
return `${protocol}//${hostname}${portStr}/.../${lastPartOfPath}${searchParamsStr}`;
} else {
return urlStr;
}
} catch (e) {
return urlStr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment