diff options
Diffstat (limited to 'src/app/utils/text_utils.js')
| -rw-r--r-- | src/app/utils/text_utils.js | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/src/app/utils/text_utils.js b/src/app/utils/text_utils.js new file mode 100644 index 0000000..1f987ec --- /dev/null +++ b/src/app/utils/text_utils.js @@ -0,0 +1,93 @@ +/** + * Text and sorting utilities. + * @module app/utils/text_utils + */ + +/** + * Remove HTML-unfriendly characters from a string + * @param {string} text string to sanitize + * @return {string} the sanitized string + */ +export const sanitize = (text) => + String(text || "").replace(new RegExp("[<>&]", "g"), ""); + +/** + * Remove non-alphanumerics from a string + * @param {string} text string to sanitize + * @return {string} the sanitized string + */ +export const sanitizeName = (text) => + String(text || "").replace(new RegExp("[^-_a-zA-Z0-9]", "g"), ""); + +/** + * Remove HTML from a string + * @param {string} text string to sanitize + * @return {string} the sanitized string + */ +export const stripHTML = (text) => String(text || "").replace(/<[^>]+>/g, ""); + +/** + * Replace HTML special characters with entitites + * @param {string} text string to sanitize + * @return {string} the sanitized string + */ +export const sanitizeHTML = (text) => + String(text || "") + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">"); + +/** + * Capitalize a single word + * @param {string} text string to capitalize + * @return {string} the capitalized word + */ +export const capitalizeWord = (text) => + text.charAt(0).toUpperCase() + text.slice(1); + +/** + * Capitalize all words in a string + * @param {string} text string to capitalize + * @return {string} the capitalized string + */ +export const capitalize = (text) => + String(text || "") + .split(" ") + .map(capitalizeWord) + .join(" "); + +/** + * Convert a phrase to a slug + * @param {string} text string to slugify + * @return {string} the slugified string + */ +export const slugify = (text) => + String(text || "") + .toLowerCase() + .replace(/\s/g, "-") + .replace(/[^-_a-zA-Z0-9]/g, "-") + .replace(/-+/g, "-"); + +/** + * Sort function, sort strings ascending (a -> z) + */ +// eslint-disable-next-line id-length +export const sortString = (a, b) => a[0].localeCompare(b[0]); + +/** + * Sort function, sort strings descending (z -> a) + */ +// eslint-disable-next-line id-length +export const sortStringDescending = (a, b) => b[0].localeCompare(a[0]); + +/** + * Sort function, sort numbers ascending (0 -> 1) + */ +// eslint-disable-next-line id-length +export const sortNumeric = (a, b) => a[1] - b[1]; + +/** + * Sort function, sort numbers descending (1 -> 0) + */ +// eslint-disable-next-line id-length +export const sortNumericDescending = (a, b) => b[1] - a[1]; |
