Files
kjol/web/basic.ts

56 lines
1.5 KiB
TypeScript

export function capitalizeFirstLetter(input: string): string {
return input.charAt(0).toUpperCase() + input.slice(1);
}
export function toSnakeCase(input: string): string {
return input
.replace(/([a-z])([A-Z])/g, "$1_$2")
.replace(/[\s\-]+/g, "_")
.toLowerCase();
}
export function snakeCaseToTitleCase(input: string): string {
return input
.split("_")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
// Strips non-numeric characters from a string including spaces.
export function sanitizeNum(input: string): string {
return input.replaceAll(/[^\d]+/g, "");
}
// Strips non-alphanumeric, non-space characters from a string.
export function sanitizeAlphaNum(input: string): string {
return input.replaceAll(/[^a-zA-Z0-9 ]+/g, "");
}
// Strips non-alphanumeric characters from a string including spaces.
export function sanitizeAlphaNumStrict(input: string): string {
return input.replaceAll(/[^a-zA-Z0-9]+/g, "");
}
export function numberToStringWithCommas(n: number):string {
var str = n.toString();
var negative = false;
if (str.startsWith("-")) {
negative = true;
str = str.slice(1);
}
var result = "";
for (let i=0; i < str.length; i++) {
if (i > 0 && (str.length - i)%3 === 0) {
result += ",";
}
result += str[i]
}
if (negative) {
result = "-" + result;
}
return result;
}