Search code examples
javascriptimagesrc

Problem with Javasript setting an image via src with a variable


I'm trying to set an image to a html element with src. The image is a spotify album cover of which I get the link from spotify (the link looks like this: https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828)

This is my code:

const getSongData = () => {
    currentlyPlaying= localStorage.getItem("currentlyPlaying");
    songDuration = localStorage.getItem("songDuration");
    currentAlbum = localStorage.getItem("currentAlbum");
    currentArtist = localStorage.getItem("currentArtist");
    currentAlbumCover = localStorage.getItem("currentAlbumCover");

    document.getElementById('currentlyPlaying').innerHTML = currentlyPlaying;
    document.getElementById('songDuration').innerHTML = (`${(songDuration/1000)/60}:${(songDuration/1000)%60}`);
    document.getElementById('currentAlbum').innerHTML = currentAlbum;
    document.getElementById('currentArtist').innerHTML = currentArtist;
    document.getElementById('currentAlbumCover').src = currentAlbumCover;
    //console.log(currentAlbumCover);
}

So the variable currentAlbumCover contains the link and this doesn't work I get this error message:

enter image description here

The funny thing is it works just fine if I put the link in directly like this:

document.getElementById('currentAlbumCover').src = 'https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828';

Solution

  • I found the error! The string that I got from Spotify starta and ends with a quote and I didn't notice that in the console... This line fixes it:

    currentAlbumCover = localStorage.getItem("currentAlbumCover").replace(/\"/g, '');