0

I have a function that receives values for 2 parameters: string and filter.

I need to check if the string contains the filter value. This is my current code, which works fine:

function matcher(string, filter) {
    if(string.search(new RegExp(filter, 'i')) < 0) {
        return false;
    } else {
        return true;
    }
}

matcher("french flag", "fren");

But, the matcher function should only return true, if the filter matches the beginning of the string. For example, these cases should be true:

matcher("french flag", "fr");
matcher("french flag", "fre");
matcher("french flag", "frenc");

But these cases should be false (currently the function returns true on these ones):

matcher("french flag", "fla");
matcher("french flag", "ren");
matcher("french flag", "enc");

Thanks for your help.

Andres SK
  • 10,779
  • 25
  • 90
  • 152
  • Why not just use [`String#startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)? The function is just obfuscating the `search` call, and there's no need to do `if (something) { return true; } else { return false; }`, just `return something;`. – ggorlen Sep 29 '19 at 23:31
  • @ggorlen is not widely supported https://caniuse.com/#search=startsWith and is case sensitive :( – Andres SK Sep 30 '19 at 03:41
  • 1
    Fair enough. How about `new RegExp("^" + filter, "i")`. Use the carat to anchor to the start of line. – ggorlen Sep 30 '19 at 03:44

0 Answers0