Skip to content

Instantly share code, notes, and snippets.

@alexalannunes
Created June 16, 2024 14:54
Show Gist options
  • Save alexalannunes/3b1cb7f0b2f51cc151ef54af364b9501 to your computer and use it in GitHub Desktop.
Save alexalannunes/3b1cb7f0b2f51cc151ef54af364b9501 to your computer and use it in GitHub Desktop.
convert string to slug to use as url, id or other case
const REGEX_HELPER = {
ALL_NON_DOT_DIGITS: /[^0-9.-]+/g,
ALL_NON_NUMBERS: /\D+/g,
ANY_EACH_UPPERCASE_LETTER: /([A-Z])/g,
NUMBER_WITH_PX_SUFFIX: /(-?\d+)px/,
ONLY_ALLOWED_CHARACTERS: /^[A-Za-z0-9/;&\-_ ]+$/,
ONLY_ALPHANUMERIC_AND_SPECIAL_CHARS: /^[A-Za-z0-9/\-_@!#$% ]+$/,
ONLY_POSITIVE_DECIMAL: /^\d+(\.\d{0,2})?$/,
ONLY_POSITIVE_INTEGER_NUMBERS: /^\d+$/,
ONLY_POSITIVE_INTEGER_NUMBERS_WITHOUT_LEADING_ZERO: /^[1-9]\d*$/,
ONLY_POSITIVE_WITH_TWO_LEADING_ZEROS:
/^[+]?([0-9]+(?:[.][0-9]{0,2})?|\.[0-9]{0,2})$/,
ONLY_POSITIVE_WITH_LEADING_ZEROS: /^[+]?([0-9]+(?:[.][0-9]+)?|\.[0-9]+)$/,
ONLY_UNALLOWED_CHARACTERS: /[^A-Za-z0-9/;&\-_ ]/g,
POSITIVE_NEGATIVE_INTEGER_NUMBERS: /^-?\d{0,}$/,
REMOVE_EXTRA_SPACES: /\s+/g,
STRING_AFTER_LAST_COMMA: /,\s([^,]+)$/,
NON_KEBAB_CASE: /[^A-Za-z0-9-]/g,
NON_ALPHANUMERIC_UNDERSCORE: /[^A-Za-z0-9_ ]/g,
};
/**
*
* Transforms string in a clean slug
* Default separator is "-" (kekab-case)
*
* @param {string} value - the unparsed value
* @param {string} separator - the tokens separator
* @returns {string} cleaned string
*/
export const toSlug = (value: string, separator = '-') => {
// Convert the string to normalized NFD form (Unicode)
const normalizedValue = (value || '').normalize('NFD');
// Remove accents through the unicode character range
const withoutAccents = normalizedValue.replace(/[\u0300-\u036f]/g, '');
// Convert to lowercase
const lowercased = withoutAccents.toLowerCase();
// Remove extra spaces, transforming more than one space into a single space
const trimmed = lowercased.trim().replace(/[\s\t\n]+/gm, ' ');
// Replace slashes with underscores to avoid collision
const withoutSlashes = trimmed.replace(/\//, '_');
// Remove non-alphanumeric characters and underscores
const alphanumericOnly = withoutSlashes.replace(
REGEX_HELPER.NON_ALPHANUMERIC_UNDERSCORE,
''
);
// Replace spaces with a specific separator (default is '-')
const result = alphanumericOnly.replace(/\s/g, separator);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment