Here's a simple JavaScript function that uses regular expressions to parse the input string and create the AST:
function parseStyleString(input) {
const pseudoMatch = input.match(/^(.*?):/);
const pseudo = pseudoMatch ? pseudoMatch[1] : '';
const propertyValueMatch = input.match(/^hover:|([^:]+):([^/]+)\/([^ ]+)$/);
if (propertyValueMatch) {
const [, property, value, modifier] = propertyValueMatch;
return {
pseudo,
property: property,
value,
modifier,
};
}
const propertyMatch = input.match(/^([^:]+):([^ ]+)$/);
if (propertyMatch) {
const [, property, value] = propertyMatch;
return {
pseudo,
property,
value,
modifier: '',
};
}
return {};
}
You can use this function by calling it with the style string as the argument, like so:
console.log(parseStyleString('hover:bg-gray-500/50'));
// Outputs: { pseudo: 'hover', property: 'bg', value: 'gray-500', modifier: '50' }
console.log(parseStyleString('color-red-100'));
// Outputs: { pseudo: '', property: 'color', value: 'red-100', modifier: '' }
This function first checks if the input string starts with a pseudo-class (e.g., "hover:"). If it does, it extracts the pseudo-class and then checks if the remaining string matches the pattern for a property value with a modifier (e.g., "bg-gray-500/50"). If it does, it extracts the property, value, and modifier. If the input string doesn't start with a pseudo-class, it checks if it matches the pattern for a property value without a modifier (e.g., "color-red-100"). If it does, it extracts the property and value. If the input string doesn't match any of these patterns, the function returns an empty object.