Skip to content

Instantly share code, notes, and snippets.

@quantizor
Last active February 22, 2018 17:03
Show Gist options
  • Save quantizor/292e9960733a3901dc2088677facaba7 to your computer and use it in GitHub Desktop.
Save quantizor/292e9960733a3901dc2088677facaba7 to your computer and use it in GitHub Desktop.
SVG -> Data URI for CSS embedding
function prepareSVGAsDataURI(rawSVG) {
const prefix = 'data:image/svg+xml,';
let svg = encodeURIComponent(rawSVG.replace(/\n+/g, ''));
// restore ASCII-safe characters
svg = svg.replace(/%20/g, ' '); // spaces
svg = svg.replace(/%3D/g, '='); // equal signs
svg = svg.replace(/%3A/g, ':'); // colons
svg = svg.replace(/%2F/g, '/'); // slashes
// replace quotes with apostrophes (may break certain SVGs)
// this allows the consumer to safely encase the data URI string in double quotes as we do in JSX templates, etc.
svg = svg.replace(/%22/g, "'");
return `${prefix}${svg}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment