Skip to content

Instantly share code, notes, and snippets.

@JacobDB
Forked from B-iggy/inline-svg-function.scss
Created January 26, 2017 17:45
Show Gist options
  • Save JacobDB/0ffffaf8e772c12acf7102edb8a302be to your computer and use it in GitHub Desktop.
Save JacobDB/0ffffaf8e772c12acf7102edb8a302be to your computer and use it in GitHub Desktop.
Inline SVG function [SASS]
// Replace letters
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
// Encode symbols
@function url-encode($string) {
$map: (
"%": "%25",
"<": "%3C",
">": "%3E",
" ": "%20",
"!": "%21",
"*": "%2A",
"'": "%27",
'"': "%22",
"(": "%28",
")": "%29",
";": "%3B",
":": "%3A",
"@": "%40",
"&": "%26",
"=": "%3D",
"+": "%2B",
"$": "%24",
",": "%2C",
"/": "%2F",
"?": "%3F",
"#": "%23",
"[": "%5B",
"]": "%5D"
);
$new: $string;
@each $search, $replace in $map {
$new: str-replace($new, $search, $replace);
}
@return $new;
}
// Format the SVG as a URL
@function inline-svg($string) {
@return url('data:image/svg+xml,#{url-encode($string)}');
}
@raybrownco
Copy link

Nice work. Functions perfectly. 👍

@gemmadlou
Copy link

Forked! Thank you

@po5i
Copy link

po5i commented Sep 5, 2018

This is awesome!

@nicarslayer
Copy link

write please how to use

@d3zza
Copy link

d3zza commented Dec 6, 2018

Nice one! Thank you.

@Michelangelo9
Copy link

Thanks! This saved me some time to figure out. Cheers 🍺

@diskomanuelle
Copy link

Hi Thanks for this function !

@Lukom
Copy link

Lukom commented Dec 7, 2021

it appears that it's not mandatory to escape all symbols, eg.

data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath d='M224%20387.814V512L32 320l192-192v126.912C447.375 260.152 437.794 103.016 380.93 0 521.287 151.707 491.48 394.785 224 387.814z'/%3E%3C/svg%3E

is valid

so this function can be simplified:

  ...
  $map: (
          "%": "%25",
          "<": "%3C",
          ">": "%3E",
          '"': "\'",
          "&": "%26",
          "#": "%23"
  );
  ...
@function inline-svg($string) {
  @return url("data:image/svg+xml,#{url-encode($string)}");
}

@g-30
Copy link

g-30 commented Jan 4, 2022

@Lukom thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment