Regex to match item in csv string

I have a string that’s a csv of 5-6 digit numbers. I.e. ‘12345,67890,555555’. There can also be spaces in before/after a number. So ‘ 123456 , 12345,22222’.

I was initially doing my regex match of `Trying to see in ‘12345’ is in a csv

 const csv = '12345,67890,555555';
   const regex = /12345/
   regex.test(csv); 

`

But I’m seeing this introduces false positive of if another character can exist before the test. I.e. It’s also matching on ‘012345’, etc.

What’s the best way to search here? I’m doing my matches with regex matches with Mongo DB filters btw

Answer

I would just adjust your regex to use anchors. Anchors restrict where your match can be, without matching any additional characters. In this case, I believe you need to anchor to a word boundary on both sides, which will require that the character on either side of 12345 is not a “word character” (Any alphanumeric character or an underscore). This means it could be next to a comma, space, beginning of line, or end of line in your case. The token for a word boundary is b. This makes your regex: const regex = /b12345b/.

You can also avoid using regex by writing your own test() function. Assuming you know that your CSV is comma-delimited, you can split the string by commas, store the result in an array, and then loop through that array, checking if each element is equal to the string you’re looking for. This could be implemented like so:

function test(needle, haystack) {
    let arr = haystack.split(",");

    for (let str of arr) {
        if (str === needle) {
            return true;
        }
    }

    return false;
}