Created
December 1, 2022 16:46
-
-
Save HaNdTriX/e6724ff6f7e8c389c97ae58f58eda888 to your computer and use it in GitHub Desktop.
Convert relative paths to absolute paths inside html string
This file contains hidden or 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
/** | |
* Convert relative paths to absolute paths | |
* @author HaNdTriX | |
* @param {string} html - HTML string | |
* @param {string} baseUrl - base url to prepend to relative paths | |
* @param {string[]} [attributes] - attributes to convert | |
* @returns {string} | |
*/ | |
function absolutify( | |
html, | |
baseUrl, | |
attributes = [ | |
"href", | |
"src", | |
"srcset", | |
"cite", | |
"background", | |
"action", | |
"formaction", | |
"icon", | |
"manifest", | |
"code", | |
"codebase", | |
] | |
) { | |
// Build the regex to match the attributes. | |
const regExp = new RegExp( | |
`(?<attribute>${attributes.join( | |
"|" | |
)})=(?<quote>['"])(?<path>.*?)\\k<quote>`, | |
"gi" | |
); | |
return html.replaceAll(regExp, (...args) => { | |
// Get the matched groupes | |
const { attribute, quote, path } = args[args.length - 1]; | |
// srcset may have multiple paths `<url> <descriptor>, <url> <descriptor>` | |
if (attribute.toLowerCase() === "srcset") { | |
const srcSetParts = path.split(",").map((dirtyPart) => { | |
const part = dirtyPart.trim(); | |
const [path, size] = part.split(" "); | |
return `${new URL(path.trim(), baseUrl).toString()} ${size || ""}`; | |
}); | |
return `${attribute}=${quote}${srcSetParts.join(", ")}${quote}`; | |
} | |
const absoluteURL = new URL(path, baseUrl).href; | |
return `${attribute}=${quote}${absoluteURL}${quote}`; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment