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:
JavaScript
x
6
1
function svgFileToString('./icon.svg'){
2
3
4
return `<svg>...</svg>`
5
}
6
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.
JavaScript
1
14
14
1
function svgFileToString(iconpath){
2
fetch(iconpath)
3
.then(response => response.text())
4
.then(text => {
5
console.log(text);
6
// do whatever
7
});
8
}
9
10
//svgFileToString('/icon.svg');
11
12
// for testing here on ST:
13
14
svgFileToString('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iZ3JlZW4iIC8+Cjwvc3ZnPgo=');