2
0
mirror of https://github.com/iconify/iconify.git synced 2024-12-13 22:18:24 +00:00
iconify/packages/utils/src/svg/url.ts
2022-05-01 09:04:54 +03:00

27 lines
746 B
TypeScript

/**
* Encode SVG for use in url()
*
* Short alternative to encodeURIComponent() that encodes only stuff used in SVG, generating
* smaller code.
*/
export function encodeSVGforURL(svg: string): string {
return (
svg
.replace(/"/g, "'")
.replace(/%/g, '%25')
.replace(/#/g, '%23')
// .replace(/{/g, '%7B') // not needed in string inside double quotes
// .replace(/}/g, '%7D') // not needed in string inside double quotes
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/\s+/g, ' ') // Replace all whitespace with space to get rid of '\r', '\n' and '\t'
);
}
/**
* Generate url() from SVG
*/
export function svgToURL(svg: string): string {
return 'url("data:image/svg+xml,' + encodeSVGforURL(svg) + '")';
}