1

i am trying to filter this json API, using regex... i receive some json, when i input some letter for example "j" in input field, i want to return author of quote for instance "jessie", and it works perfectly, but i have problem, if i want to return error alert, if in this json APi there are not author names for letter "f" , what i can to do, i tried everything but can't figure out what happens to me :(

//my HTML looks like this:

 <div class="container mt-5" ">
            <div class="row">
                <div class="col-md-4 m-auto">
                    <h3 class="text-center mb-3" style="color: rgb(10, 10, 10); font-family: 'Anton', sans-serif;">
                        Search Characters Quotes by their names
                    </h3>
                    <div class="form-grup">
                        <input type="text" class="imput form-control form-control-lg"   title="Only Alphabets" id="search" placeholder="search">
                    </div>
                    <div id="match-list"></div>
                </div>
            </div>
        </div>

//my javascript looks same

const search = document.getElementById("search");
const ResultHtml = document.getElementById("match-list");



 const request = async () => {
                const response = await fetch("https://www.breakingbadapi.com/api/quotes");
                const data = await response.json();
                renderYourData(data, search.value);

     }

     const renderYourData = (data, searchtext) => {
        const x= data.filter(film=>{
            const regex = new RegExp(`^${searchtext}`, 'gi');
            return film.author.match(regex)});


            function retquote(){
                ResultHtml.innerHTML =`<div class="some">${x.map(function(bra){
                    return `<p>${bra.author}</p>`
                }).join("") } </div>`
            }
             retquote();
    }


     window.addEventListener('load', function() {
                request();          
     });

search.addEventListener('input',request) 


1 Answer 1

1

Change your retquote function to check if array length exist, if yes display the results otherwise put a default error message

Demo: https://jsfiddle.net/utnqeLmf/

 function retquote() {
        if (x.length) {
          ResultHtml.innerHTML = `<div class="some">${x.map(function(bra){
                        return `<p>${bra.author}</p>`
                    }).join("") } </div>`
        } else {
          ResultHtml.innerHTML = 'no records found'
        }
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.