skip to Main Content

This is part of a block of code to get a response of a list of games and details about each of them as JSON data from IGDB’s API:

.then(response => {
    const collections = response.data;
    const images = [];
        
    collections.forEach(collection => {
      collection.cover.url.replace('t_thumb', 't_1080p')
      // let imageURL = collection.cover.url;
      // imageURL.replace('t_thumb', 't_1080p');
      // images.push(imageURL);
    })
})

In IGDB’s database, they have different sizes and qualities for the game’s cover, and you can access each type by changing a part of the URL from t_thumb to t_1080p. I tried to change that part of the URL by using forEach and .replace() as shown in the code, but the string does not change. I also tried adding each URL to a new array one by one by copying each element, replacing part of the string, and then inserting it into the new array (the commented-out code) but that did not work either. How can I change part of each string in the collections list?

3

Answers


  1. The String.replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

    Try this :

    collection.cover.url = collection.cover.url.replace('t_thumb', 't_1080p')
    

    Live Demo :

    let collections = [{
      cover: {
        url: 'alpha'
      }
    }, {
      cover: {
        url: 't_thumb'
      }
    }, {
      cover: {
        url: 'beta'
      }
    }, {
      cover: {
        url: 't_thumb'
      }
    }, {
      cover: {
        url: 't_thumb'
      }
    }];
    
    collections.forEach(collection => {
      collection.cover.url = collection.cover.url.replace('t_thumb', 't_1080p')
    });
    
    console.log(collections);
    Login or Signup to reply.
  2. Since strings in javascript are immutable, you can’t modify the original string.

    string.replace()
    

    returns a new string after the modification. to get the changed string you need to assign the value returned from the replace() to the variable.

    you can do it like this

    collection.cover.url = collection.cover.url.replace('t_thumb', 't_1080p')
    
    Login or Signup to reply.
  3. You can use map with spread operator and replace:

     const updatedCollections = collections.map(el => ({
        ...el,
        cover: { ...el.cover, url: el.cover.url.replace('t_thumb', 't_1080p') },
      }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search