-1

I want to check if a string-variable (called string) matches the following string: L-62000-64-000_0

My code looks like this:

let string = "L-62000-64-000_05641";
let part = 64;
const filter = new RegExp("^L-\d{5}-${part}-.+");
if (string.match(filter)) {
        console.log("yes");
}

It is important, that the string starts with "L-". After this there should be a number with five digits and again a hyphen. The following two digits depend on a variable. After the variable there is again a hyphen. The rest of the string is not important for me. That's why I use the ".+"

The problem is, that this doesn't work and i don't know why...

stoex
  • 81
  • 6
  • 2
    `const filter = new RegExp("^L-\\d{5}-" + part + "-.+");`. It does not work because you are using a variable as if you had a template literal, but you are using a regular string literal. Another way: ``const filter = new RegExp(`^L-\\d{5}-${part}-.+`);`` – Wiktor Stribiżew Dec 07 '22 at 13:22
  • 1
    `let string = L-62000-64-000_05641;` should be `let string = "L-62000-64-000_05641";` – WOUNDEDStevenJones Dec 07 '22 at 13:23

2 Answers2

0

if you want to use the part variable in the string, you need to use `` instead of ""

const filter = new RegExp(`^L-\d{5}-${part}-.+`);
rszf
  • 166
  • 1
  • 8
0

You also need to add double \\ in this case

let string = 'L-62000-64-000_05641';
let part = 64;
const filter = new RegExp(`^L-\\d{5}-${part}-.+$`);
if (string.match(filter)) {
        console.log("yes");
} else {
  console.log("no");
}
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43