File: /var/www/quadcode/one-time-popup/src/utils/assets-path-replacer/replaceAssetsPath.ts
export function updateAssetPathsWithRegex(
input: string,
baseUrl: string = import.meta.env.VITE_BASE_URL,
): string {
let output = input;
if (!baseUrl.endsWith('/')) {
baseUrl += '/';
}
function replacePaths(
regex: RegExp,
replacer: (start: string, path: string, end: string) => string,
) {
output = output.replace(regex, (_, start, path, end) => replacer(start, path, end));
}
function processSrcset(srcset: string): string {
return srcset
.split(',')
.map((part) => {
const [url, descriptor] = part.trim().split(/\s+/, 2);
if (url.startsWith('/')) {
const newUrl = baseUrl + url.slice(1);
return descriptor ? `${newUrl} ${descriptor}` : newUrl;
}
return part.trim();
})
.join(', ');
}
replacePaths(
/(<img[^>]*\s+src=["'])(\/[^"']+)(["'][^>]*>)/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
replacePaths(
/(<source[^>]*\s+src=["'])(\/[^"']+)(["'][^>]*>)/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
replacePaths(
/(<audio[^>]*\s+src=["'])(\/[^"']+)(["'][^>]*>)/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
replacePaths(
/(<video[^>]*\s+poster=["'])(\/[^"']+)(["'][^>]*>)/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
replacePaths(
/(<img[^>]*\s+srcset=["'])([^"']+)(["'][^>]*>)/gi,
(start, srcsetContent, end) => `${start}${processSrcset(srcsetContent)}${end}`,
);
replacePaths(
/(<source[^>]*\s+srcset=["'])([^"']+)(["'][^>]*>)/gi,
(start, srcsetContent, end) => `${start}${processSrcset(srcsetContent)}${end}`,
);
replacePaths(
/(background-image:\s*url\(["']?)(\/[^"')]+)(["']?\))/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
replacePaths(
/(url\(["']?)(\/[^"')]+)(["']?\))/gi,
(start, path, end) => `${start}${baseUrl}${path.slice(1)}${end}`,
);
return output;
}