Search code examples
javascriptjqueryimdb

How to strip a string from unwanted parts?


Given an url like this:

https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ@@._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg

How do i get it to be like

https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ@@._V1._CR34,44_AL_.jpg

The issue I am having is with retrieving IMDB poster images, using this:

$('form[name="search-imdb"]').on("submit", function(e) {
  var form = $(this);
  e.preventDefault();
  $.ajax({
     url: "http://imdb.wemakesites.net/api/search",
     data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
     crossDomain: true,
     dataType: "jsonp",
     success: function(data) {
       window.console.log(data);
     }
  });
});

I get a json response like:

"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_UX32_CR0,0,32,44_AL_.jpg"

I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:

function imdbLoad() {
  var form = $("#usp-title").val();
  var encodedTerm = encodeURIComponent(form);
        $.ajax({
           url: "http://imdb.wemakesites.net/api/search",
           data: {
             q: encodedTerm
           },
           crossDomain: true,
           dataType: "jsonp",
           success: function(data) {
             $("#imdb").empty();
             $.each(data.data.results, function(i, items) {
               $("#imdb").append('<h2>'+i+'</h2>');
               $.each(items, function(k, item) {
                 $("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
               });
             });
           }
        });
}

Unless anyone has any other way to grab the poster url


Solution

  • You can either use regex to replace string part that is not required

    var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ@@._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
    var regex = /,.*(?=,)/g;
    console.log(url.replace(regex, ''))

    or split using comma(,) and join first and last part.

    var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ@@._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
    
    var parts = url.split(',');
    console.log(parts[0] + ',' + parts.pop())