simple function for filter words on page

I write function for search title of state, and everything works perfect but when i type letters in search bar filter look for all letters in word. I want make filter search from beginning word.

example

if i type an filter result will be c'an'ada he find an and that its ok but i want to check only from beginning

function filterNames() {
    let filterValue = document.getElementById('filterInput').value.toUpperCase();
    let kartice = allContinet;
    let h2 = document.querySelectorAll('h2');

    for (let i=0;i<h2.length;i++) {
        let name = h2[i].getElementsByClassName("ime-zemlje");

        if (name[0].innerHTML.toUpperCase().indexOf(filterValue) > -1) {
            kartice[i].style.display = '';
        } else {
            kartice[i].style.display = 'none';
        }

    }
}

Upvotes: 2

Views: 336

Answers (3)

J CHEN
J CHEN

Reputation: 494

function filterNames() {
    var filterValue = document.getElementById('filterInput').value;
    
    //console.log(filterValue);
    var h2 = document.querySelectorAll('h2.ime-zemlje');//for h2+sime-zemlje class
    for (var i=0;i<h2.length;i++) {
        //console.log(h2[i].innerText);
        if(filterValue.length<1){
          h2[i].innerHTML=h2[i].innerText;
          continue;
        }
        var GD=h2[i].innerText;
        var QQ="";
        var pos = 0;
        while (pos != -1) {
          pos = GD.indexOf(filterValue, 0);
          //console.log(pos);
          if(pos!=-1){
            QQ+=GD.substring(0, pos);//Add Back Normal Word
            QQ+='<span style="color: red;">'+GD.substring(pos, pos+filterValue.length)+'</span>';//Add Back Search Word And Be Colorful
            GD=GD.substring(pos+filterValue.length, GD.length);//Remove Add Back Word Then Next Loop Not Search Again
          }
        }
        h2[i].innerHTML=QQ+GD;
        
        
        
        
        //console.log(QQ+GD);

    }
}
<input type="text" id="filterInput" onchange="filterNames()"></input>
<h2 class="ime-zemlje">I Love Little Girl</h2>
<h2 class="ime-zemlje">I Love Loli</h2>
<h2 class="QQQQQQ">I Scared FBI</h2>

Key In Love Or I you will See what you want

Upvotes: 0

Ankur Mittal
Ankur Mittal

Reputation: 65

You can use .search method of String.

So your if condition will become

if(name[0].innerHTML.toUpperCase().search(new RegExp(`^${filterVal}`)) === 0)

search has good browser support as well

Upvotes: 1

adiga
adiga

Reputation: 35222

You can use startsWith instead of indexOf

if (name[0].innerHTML.toUpperCase().startsWith(filterValue)) { }

This is a ES2015+ feature. If it is not supported in your browser, you can add this polyfill

Or you can use regex with a ^ and i flag to match only those strings which start with filterValue irrespetive of case:

var regex = new RegExp('^' + filterValue, 'i')
if(regex.test(name[0].innerHTML)) {

}

Upvotes: 1

Related Questions