Eidos

svgToDataUri

By: Mayne

Install Latest (v0.0.1)

Converts an SVG string into a Data URI format.

/**
 * Converts an SVG string into a Data URI format.
 * @param {string} svgString - The SVG content as a string to be converted into a Data URI.
 * @returns {string} A Data URI string representing the SVG, or an empty string if the input is invalid.
 * @example
 * svgToDataUri('<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="red" /></svg>')
 * // Returns: 'data:image/svg+xml;charset=utf-8,%3Csvg%20width%3D%22100%22%20height%3D%22100%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2240%22%20fill%3D%22red%22%20/%3E%3C/svg%3E'
 */
function svgToDataUri(svgString) {
  // Handle null or undefined input
  if (svgString === null || svgString === undefined || typeof svgString !== 'string') {
    return '';
  }

  // Trim the input string to remove unnecessary whitespace
  const trimmedSvg = svgString.trim();

  // If the string is empty after trimming, return an empty string
  if (trimmedSvg.length === 0) {
    return '';
  }

  // Encode the SVG string to URI format
  const encodedSvg = encodeURIComponent(trimmedSvg)
    // Replace specific characters to ensure compatibility with Data URI
    .replace(/'/g, '%27')
    .replace(/"/g, '%22');

  // Construct the Data URI with the correct MIME type for SVG
  return `data:image/svg+xml;charset=utf-8,${encodedSvg}`;
}

Information

Author
Mayne
Type
udf
Latest Version
0.0.1
Last Updated
05/17/2025
Published
05/17/2025

Version History

  • v0.0.1 05/17/2025