Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Created December 1, 2022 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaNdTriX/e6724ff6f7e8c389c97ae58f58eda888 to your computer and use it in GitHub Desktop.
Save HaNdTriX/e6724ff6f7e8c389c97ae58f58eda888 to your computer and use it in GitHub Desktop.
Convert relative paths to absolute paths inside html string
/**
* 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