Last active
October 30, 2017 23:02
-
-
Save grantcodes/5eb16ffc6246d4b4c05b01e93c369396 to your computer and use it in GitHub Desktop.
Simple function to get all rel links from a html string
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
export default function (htmlString, url) { | |
let rels = {}; | |
let baseUrl = url; | |
const doc = new DOMParser().parseFromString(htmlString, 'text/html'); | |
const baseEl = doc.querySelector('base[href]'); | |
const relEls = doc.querySelectorAll('[rel][href]'); | |
if (baseEl) { | |
const value = baseEl.getAttribute('href'); | |
const url = new URL(value, url); | |
baseUrl = url.toString(); | |
} | |
if (relEls.length) { | |
relEls.forEach((relEl) => { | |
const names = relEl.getAttribute('rel').toLowerCase().split("\\s+"); | |
const value = relEl.getAttribute('href'); | |
if (names.length && value !== null) { | |
names.forEach((name) => { | |
if (!rels[name]) { | |
rels[name] = []; | |
} | |
const url = new URL(value, baseUrl).toString(); | |
if (rels[name].indexOf(url) === -1) { | |
rels[name].push(url); | |
} | |
}); | |
} | |
}); | |
} | |
return rels; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment