var myPattern = /^(.*)/ig; var matchStation = mass.filter(function (station) { if (station.search(myPattern) > 0) return station; }); matchStation.forEach(el => console.log(el)); 

mass - an array of 160 stations. search() does not work (the matchStation array matchStation always empty). What am I doing wrong?

    1 answer 1

    Actually .search works.

    The specified regular expression actually matches the beginning of the string, and search will return 0 in all cases.

    Because of this, the check (station.search(myPattern) > 0) always false and from the function passed to filter always returns undefined , which corresponds to false .

    Therefore, the resulting array is always empty.

    • I do not understand why search returns 0? After all, the pattern /^(.*)/ig matches any string. Isn't 1 supposed to return? - Vitaliy Shebanits
    • Understand the mistake, thanks !!!!!!!!!!!!!!!!!!! I thought that if he found a coincidence, then he returns 1 - Vitaly Shebanits
    • @ VitaliyShebanits, no, search, as well as IndexOf returns the index of the found substring, or -1 if nothing is found - Grundy