Skip to content
Advertisement

Split URL that contains more than one comma javascript

Basically I try to split a string of URL that contains more than one Comma, but the result turns out to be like this:

{
            "photoUrl": [
                "https://m.media-amazon.com/images/M/MV5BMTU4MTgxOTQ0Nl5BMl5BanBnXkFtZTgwNDI0Mjk1NDM@._V1_UY100_CR19",
                "0",
                "100",
                "100_AL_.jpg",
                "https://m.media-amazon.com/images/M/MV5BMTczMTk5MjkwOF5BMl5BanBnXkFtZTgwMDI0Mjk1NDM@._V1_UY100_CR12",
                "0",
                "100",
                "100_AL_.jpg",
                "https://m.media-amazon.com/images/M/MV5BZTFiODA5NWEtM2FhNC00MWEzLTlkYjgtMWMwNzBhYzlkY2U3XkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UX100_CR0",
                "0",
                "100",
                "100_AL_.jpg"
            ]
        },

Here is my code, is there a way to fix it….

for (let i = 0; i < data.length; i++) {
                console.log(data[i].genre[i].genre.split(","));
                New_data.push({ photoUrl: data[i].photo[i].photoUrl.split(",") });
                New_data.push({ genre: data[i].genre[i].genre.split(",") });
            }

URL Before splitted:

'https://m.media-amazon.com/images/M/MV5BMTU4MTgxOTQ0Nl5BMl5BanBnXkFtZTgwNDI0Mjk1NDM@._V1_UY100_CR19,0,100,100_AL_.jpg,https://m.media-amazon.com/images/M/MV5BMTczMTk5MjkwOF5BMl5BanBnXkFtZTgwMDI0Mjk1NDM@._V1_UY100_CR12,0,100,100_AL_.jpg,https://m.media-amazon.com/images/M/MV5BZTFiODA5NWEtM2FhNC00MWEzLTlkYjgtMWMwNzBhYzlkY2U3XkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UX100_CR0,0,100,100_AL_.jpg'

Advertisement

Answer

Since we know the url starts with https:// we can check each segment for it and build up url accordingly:

const text = 'https://m.media-amazon.com/images/M/MV5BMTU4MTgxOTQ0Nl5BMl5BanBnXkFtZTgwNDI0Mjk1NDM@._V1_UY100_CR19,0,100,100_AL_.jpg,https://m.media-amazon.com/images/M/MV5BMTczMTk5MjkwOF5BMl5BanBnXkFtZTgwMDI0Mjk1NDM@._V1_UY100_CR12,0,100,100_AL_.jpg,https://m.media-amazon.com/images/M/MV5BZTFiODA5NWEtM2FhNC00MWEzLTlkYjgtMWMwNzBhYzlkY2U3XkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UX100_CR0,0,100,100_AL_.jpg';

const res = {photoUrl: []};

const array = text.split(",");
let url = "";
for(let i = 0; i < array.length; i++)
{
  //if value is does not start with https:// append to current url
  if (array[i].indexOf("https://"))
  {
    url += "," + array[i];
  }
  else
  {
    if (url !== "")
      res.photoUrl.push(url);

    url = array[i];
  }
}

res.photoUrl.push(url);

console.log(res);
.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement