Last active
February 22, 2018 17:03
-
-
Save quantizor/292e9960733a3901dc2088677facaba7 to your computer and use it in GitHub Desktop.
SVG -> Data URI for CSS embedding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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