mirror of
https://github.com/FH-Complete/FHC-Core.git
synced 2026-10-12 15:04:04 +00:00
62 lines
1.7 KiB
JavaScript
62 lines
1.7 KiB
JavaScript
/**
|
|
* Makes a value safe for an HTML string. A Tabulator formatter string becomes innerHTML, therefore
|
|
* a value from the database or from an addon must not carry markup.
|
|
*/
|
|
export function escapeHtml(value) {
|
|
if (value === null || value === undefined) return '';
|
|
|
|
const replacements = {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''};
|
|
|
|
return String(value).replace(/[&<>"']/g, (character) => replacements[character]);
|
|
}
|
|
|
|
export function capitalize(string) {
|
|
if (!string) return "";
|
|
return string[0].toUpperCase() + string.slice(1);
|
|
}
|
|
|
|
export function convertCase(string, from, to) {
|
|
const possibleCases = ["kebab", "snake", "camel"];
|
|
if (
|
|
from === to ||
|
|
!possibleCases.includes(from) ||
|
|
!possibleCases.includes(to)
|
|
)
|
|
return string;
|
|
|
|
const individualWords =
|
|
from === "kebab"
|
|
? string.split("-")
|
|
: from === "snake"
|
|
? string.split("_")
|
|
: splitWordsInCamelCase(string);
|
|
|
|
const formattedIndividualWords = ["snake", "kebab"].includes(to)
|
|
? individualWords.map((word) => word.toLowerCase())
|
|
: individualWords.map((word, index) => {
|
|
if (!index) return word.toLowerCase();
|
|
return word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
|
|
});
|
|
|
|
const joinCharacter = to === "snake" ? "_" : to === "kebab" ? "-" : "";
|
|
return formattedIndividualWords.join(joinCharacter);
|
|
}
|
|
|
|
function splitWordsInCamelCase(string) {
|
|
const lastUpperCaseLetterIndex = string
|
|
.split("")
|
|
.findLastIndex((character) => {
|
|
return character.toUpperCase() === character;
|
|
});
|
|
|
|
if (lastUpperCaseLetterIndex < 1) {
|
|
return [string];
|
|
}
|
|
|
|
let splitWords = splitWordsInCamelCase(
|
|
string.slice(0, lastUpperCaseLetterIndex),
|
|
);
|
|
splitWords.push(string.slice(lastUpperCaseLetterIndex));
|
|
return splitWords;
|
|
}
|