Skip to content
Advertisement

How to get svg icon as a string from a .svg file

Is there a way to get svg icon as a string while you have the .svg file with JavaScript ?

To be more clear, I need a function which does:

function svgFileToString('./icon.svg'){
...
...
return `<svg>...</svg>`
}

Advertisement

Answer

You can use the fetch() function. The function svgFileToString() will not return anything, but you can replace console.log(text); with whatever.

For the example I’m using a data URL to replace the real path to a file.

function svgFileToString(iconpath){
  fetch(iconpath)
    .then(response => response.text())
    .then(text => {
      console.log(text);
      // do whatever
    });
}

//svgFileToString('/icon.svg');

// for testing here on ST:

svgFileToString('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iZ3JlZW4iIC8+Cjwvc3ZnPgo=');
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement