isValidIdentifier.js 933 B

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