I've written a script that extracts the @font-face declaration from CSS, and I'd now like to convert it into a javascript object. Here's an example of what the original string will look like:
{font-family:GT Alpina;font-weight:100;src:url(/next/contenthash/next/fonts/gt-alpina/thin/GT-Alpina-Standard-Thin.contenthash.3322f75174e682b58d25cca4c516f38b51edb6ef.woff2) format("woff2");font-display:swap}
Thats the string I'd like to convert into an object ^.
I tried using JSON.parse(), but it doesn't work since it's not a JSON encoded string. Is therea simple way that I'm missing to convert this string into a javascript object, or will I have to loop through it and manually convert it?
Any help is appreciated — thanks!
The key point is using regex to convert CSS to JSON format and then using JSON.parse. A description of each replace part is included in the code.
var css = '{font-family:GT Alpina;font-weight:100;src:url(/next/contenthash/next/fonts/gt-alpina/thin/GT-Alpina-Standard-Thin.contenthash.3322f75174e682b58d25cca4c516f38b51edb6ef.woff2) format("woff2");font-display:swap}';
cssObject = JSON.parse(css
.replace(/"/g, '\\"') // add \ before "
.replace(/\s*\{\s*/, '{"') // add start "
.replace(/\s*;?\s*\}\s*/, '"}') // add end "
.replace(/\s*:\s*/g, '":"') // replace : with ":"
.replace(/\s*;\s*/g, '","') // replace ; with ","
);
console.log("CSS Object: ", cssObject);
To convert keys to camel format another replace is required as the following code:
var css = '{font-family:GT Alpina;font-weight:100;src:url(/next/contenthash/next/fonts/gt-alpina/thin/GT-Alpina-Standard-Thin.contenthash.3322f75174e682b58d25cca4c516f38b51edb6ef.woff2) format("woff2");font-display:swap}';
cssObject = JSON.parse(css
.replace(/"/g, '\\"') // add \ before "
.replace(/\s*\{\s*/, '{"') // add start "
.replace(/\s*;?\s*\}\s*/, '"}') // add end "
.replace(/\s*:\s*/g, '":"') // replace : with ":"
.replace(/\s*;\s*/g, '","') // replace ; with ","
.replace(/"([^"]+)":/g, (full, property) => '"' + property.toLowerCase().replace(/-(\w)/, (a, b) => b.toUpperCase()) + '":')
);
console.log("CSS Object with Camel Format: ", cssObject);