Making function search by name and making an alert if its error

Viewed 22

this is my first time posting here, please help me. i want to make else if function to display an alert "error not found" if I search any data was not country name in array data. Here is my code below:

function searchByName(){
    
    let display = document.getElementById("data-container");
    let textInput = document.getElementById("search").value;
    display.innerHTML = "";
    let regex = new RegExp(textInput, 'ig');
  
    for(let i=0;i<country.length;i++){
      if(regex.test(`${country[i].countryRegion}`)){
        display.innerHTML += `
        <h3>${country[i].countryRegion}</h3>
        <div id="data-negara">
        <div id="konfirmasi">
        <h4>Konfirmasi</h4>
        <p>${country[i].confirmed}</p>
        </div>
        <div id="sembuh">
        <h4>Sembuh</h4>
        <p>${country[i].recovered}</p>
        </div>
        <div id="meninggal">
        <h4>Meninggal</h4>
        <p>${country[i].deaths}</p>
        </div>
        </div>
        `} else if( regex.test == false){
            alert("not found");
            break;
        }
    }
    return false;
}

2 Answers

In addition to Zai's answer, I think it would help you to remove this part of the code:

if( regex.test == false)

and leave a pure else branch, without any if in it.

Code sandbox here.

Try using trycatch, that’s the easiest solution. The current code in your method cut it and add it to the try section and manage your error handing in the catch block.

Or add an if statement

Related