[SOLVED] Filtering with regex in javascript

Issue

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.

Solution

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}

Answered By – SirThanksALot

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.