user11710915
user11710915

Reputation: 434

Cannot read property 'split' of undefined Javascript

I'm using Algolia instantsearch and I'm trying to remove public from the image url so that it can display the image. The url looks like this public/photos/436Rga0UafNBJkBe6b5X0DJL49jcife687sqqgeI.jpegon Algolia indices attributes, so the final url looks like http://127.0.0.1:8000/storage/public/photos/436Rga0UafNBJkBe6b5X0DJL49jcife687sqqgeI.jpeg. I want to remove that public so it can be http://127.0.0.1:8000/storage/photos/436Rga0UafNBJkBe6b5X0DJL49jcife687sqqgeI.jpeg. I have tried to use split('public').pop() but I get an error Cannot read property 'split' of undefined Javascript. How can I replace that?

search.addWidget(
    instantsearch.widgets.hits({
        container: '#hits',
        templates: {
            empty: 'No results',
            item: function(item) {
                return `
                <div>
                  <img src="${window.location.origin}/storage/${item.products_photos.split('public').pop()}" alt="img" class="algolia-thumb-result">
                    </div> 
                `;
            }
        }
    })
);

Upvotes: 1

Views: 440

Answers (2)

PacCol
PacCol

Reputation: 285

You can use replace :

var test = "someAdress/public/someText.jpeg";
test = test.replace("public/","");
console.log(test);

So try this :

<img src="${window.location.origin}/storage/${item.products_photos.replace("public/","");}" alt="img" class="algolia-thumb-result">

Upvotes: 2

dave
dave

Reputation: 64725

You probably need to make sure that item.products_photos exists, a simple fix would be

<img src="${window.location.origin}/storage/${(item.products_photos || '').split('public').pop()}" alt="img" class="algolia-thumb-result">
                

Upvotes: 2

Related Questions