-1

I am working currently on a project where I want to filter against an input I give. At the moment, my approach is:

var num = some.innerText;
var filter = input.value.toUpperCase().trim();

if (num.toUpperCase() == filter) {do something}

If my filter is 11 I will find only the num where the text is exactly 11, but sometimes my numbers have letters like 11A or 11B and I would like to find all instances of 11 when I filter for that. My idea is to use an or that I either check for an exact match or a match, where after the filter follows any letter character. I wanted to use regex, but this doesn't seem to work.

My regex approach

if (num.toUpperCase() == filter || num.toUpperCase() == filter + /[a-zA-Z]/) 
{do something} 

If I do this it works, but only for the letter d and I dont want to write 24 or conditions

if (num.toUpperCase() == filter || num.toUpperCase() == filter + "D") {do something}

I tried

if (num.toUpperCase().match(filter)  {do something} 

, but I dont want to find 11, 123, and so on when I enter 1 into the filter.

  • 1
    Something [like this?](https://tio.run/##ZYw7DsIwEER7n2Kp7AhIijRIyE3EDWjTrKwNMlriyL8G5ezGRnSU82bmPTFjMN5u8ZwvpTBFWNMLNEgc5VW0nJETNTJOlYiMHhbLkXxl3673tDEaUsN8Ow4nKbs6swuoavrvQOvfv4O3ADBuDY6pZ/dQ8p6MoRAOTbGX8gE) (strip any *non-digits* from both for the check) – bobble bubble Jun 24 '22 at 14:30
  • I still don't exactly know how this works, but I implemented it and it works exactly as I wanted it to work. – SirThanksALot Jun 24 '22 at 14:36

1 Answers1

1

This seems to work perfectly for my purpose. I can now get the results 11D, 11E, 11B and so on when entering 11 in to the filter and also 11D if I use that as the filter.

if (num.replace(/\D+/,'') == filter || num == filter) {do something}

  • 1
    You can read about [*non-digits* `\D` here](https://stackoverflow.com/a/19011185/5527985). Though be aware that this will also strip out floating points if there are any. Assumed you only have integers to compare. Use it on both, `input.value` and `num` instead of `toUpperCase` (not needed, only digits left). – bobble bubble Jun 24 '22 at 14:42
  • 1
    Fyi: If you expect strings like `a3Bc` (both ends `\W`) use the [`g` flag](https://stackoverflow.com/questions/12993629/what-is-the-meaning-of-the-g-flag-in-regular-expressions) for replacing multiple matches: [`num.replace(/\D+/g,'')`](https://tio.run/##bcw7DsIwEEXR3qsYKjsCkiINEnITsQNammE0iYxMHPnXINZubERJe97TfWDGQN5s8ZhPpViOsKYnaJA43kmeRZOMNnGzccJKIqOH2djIvuJ37D1vFonVcLvsh@UgZVd/ZgZVa39G0PpX6OAlAMitwVnurVuUvCYiDmHXGu9SPg) – bobble bubble Jun 24 '22 at 19:19