isValidIdentifier.cjs 1.2 KB

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