Skip to content

Instantly share code, notes, and snippets.

@tomlagier
Created April 20, 2021 21:12
Show Gist options
  • Save tomlagier/7590d84b6aed82cc2c316022957c422e to your computer and use it in GitHub Desktop.
Save tomlagier/7590d84b6aed82cc2c316022957c422e to your computer and use it in GitHub Desktop.
const fontFaceRegex = /\@font\-face\s?\{([\s\S]+?)\}/m
const fontFamilyRegex = /font\-family\:\s?['"](.+?)['"]\;?/
const urlRegex = /url\(['"]?(.+?)['"]?\)/;
const currentHost = window.location.host;
function parseFontsFromCSSString(css) {
const matches = css.matchAll(fontFaceRegex);
if(!matches) {
return
}
const results = {}
for(const match of matches) {
const rules = match[1];
// Split our declaration by line
const lines = rules
.split('\n')
.filter(v => v)
.map(line => line.trim());
// Find the font-family rule:
const familyLine = lines.find(line => line.test(fontFamilyRegex);
const family = familyLine.match(familyLine)[1];
const familyUrls = [];
// Extract the URLs from the raw lines
for(const line of lines) {
const urlMatches = line.matchAll(urlRegex);
if(!urlMatches) { continue; }
for(const urlMatch of urlMatches) {
let url = urlMatch[1];
// Add a host if one isn't specified
if(url.startsWith('/')) {
url = `${currentHost}${url}`
}
familyUrls.push(url);
}
}
results[family] = familyUrls;
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment