Created
April 20, 2021 21:12
-
-
Save tomlagier/7590d84b6aed82cc2c316022957c422e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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