Here's a possible implementation of a JavaScript parser that meets your requirements:
function parseStringToAST(input) {
const pseudo = input.match(/^:[a-z-]+/);
let propertyValue = input.replace(pseudo, '');
const propertyValueArray = propertyValue.split('-');
const property = propertyValueArray.shift();
let value = '';
let modifier = '';
if (propertyValueArray.length > 1) {
value = propertyValueArray.shift();
modifier = propertyValueArray.join('-');
} else {
value = propertyValueArray[0];
}
const ast = {
pseudo: pseudo ? pseudo[0].slice(1) : '',
property,
value,
modifier: modifier || '',
};
return ast;
}
console.log(parseStringToAST('hover:bg-gray-500/50')); // { pseudo: 'hover', property: 'bg', value: 'gray-500', modifier: '50' }
console.log(parseStringToAST('color-red-100')); // { pseudo: '', property: 'color', value: 'red-100', modifier: '' }
Explanation:
- The function
parseStringToAST takes an input string and returns an AST object.
- First, it uses a regular expression to match the pseudo class (if it exists) at the beginning of the string and removes it from the
input string.
- Next, it splits the remaining
propertyValue string by the - character to get an array of words.
- It then extracts the first word from the array as the
property name.
- If there are more than one words remaining in the array, it takes the first word as the
value and the rest of the words as the modifier (joined by -).
- If there is only one word remaining in the array, it takes that word as the
value and sets the modifier to an empty string.
- Finally, it constructs an AST object using the extracted
pseudo, property, value, and modifier values and returns it.