0

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>`
}
alirezafarin
  • 185
  • 1
  • 10
  • 1
    I think that this other [question](https://stackoverflow.com/questions/60985791/how-to-convert-image-svg-to-rendered-svg-in-javascript) can answer what you are trying to do. – Lorenz Bonat May 28 '22 at 09:49
  • 2
    I think this is what you are looking for : https://developer.mozilla.org/en-US/docs/Web/API/FileReader –  May 28 '22 at 09:50
  • See [DevTo Post ````](https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd) – Danny '365CSI' Engelman May 28 '22 at 10:09

1 Answers1

1

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=');
chrwahl
  • 8,675
  • 2
  • 20
  • 30