isValidIdentifier.mjs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const ISO_10646_CHARACTERS = /\\[0-9a-f]{1,6}(\\r\\n|[ \t\r\n\f])?/gi;
  2. const SINGLE_ESCAPED_CHARACTERS = /\\./g;
  3. const NON_WORD_OR_DASH = /[^\w-]/;
  4. const DIGIT = /\d/;
  5. /**
  6. * Returns whether a string is a valid CSS identifier
  7. * (i.e. only alphanumeric characters, `-`, and `_`;
  8. * does not have a leading digit, leading dash followed by digit, or two leading dashes)
  9. * furthermore, any escaped or ISO 10646 characters are allowed.
  10. * @see https://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
  11. * @param {string} ident
  12. * @returns {boolean}
  13. */
  14. export default function isValidIdentifier(ident) {
  15. if (!ident || ident.trim() === '') {
  16. return false;
  17. }
  18. // trims, removes ISO 10646 characters, and singly-escaped characters
  19. const trimmedIdent = ident
  20. .trim()
  21. .replace(ISO_10646_CHARACTERS, '')
  22. .replace(SINGLE_ESCAPED_CHARACTERS, '');
  23. if (NON_WORD_OR_DASH.test(trimmedIdent)) {
  24. return false;
  25. }
  26. if (DIGIT.test(trimmedIdent.charAt(0))) {
  27. return false;
  28. }
  29. if (trimmedIdent.charAt(0) === '-' && DIGIT.test(trimmedIdent.charAt(1))) {
  30. return false;
  31. }
  32. return true;
  33. }