SVG to data-uri in Javascript
by Shobhit Sharma
JavaScript
function encodeOptimizedSVGDataUri(svgString) {
var uriPayload = encodeURIComponent(svgString) // encode URL-unsafe characters
.replace(/%0A/g, '') // remove newlines
.replace(/%20/g, ' ') // put spaces back in
.replace(/%3D/g, '=') // ditto equals signs
.replace(/%3A/g, ':') // ditto colons
.replace(/%2F/g, '/') // ditto slashes
.replace(/%22/g, "'"); // replace quotes with apostrophes (may break certain SVGs)
return 'data:image/svg+xml,' + uriPayload;
};
console.log(
encodeOptimizedSVGDataUri(
'<svg fill="#39464E" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/><path d="M0 0h24v24H0z" fill="none"/></svg>'
)
)