0

I have been trying to get a regex working where I can check whether the naming scheme of an ID follows the correct format. But I want to be able to change the format using a variable. The regex combination itself works, but as soon as I tried to add in a variable, it seems to stop functioning. This version seems to work:

const id = $("#div-1-name-1").attr("id");
const regex = new RegExp(/^div-\d-name-\d$/);

console.log(regex.test(id)); // returns true as expected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="div-1-name-1"></div>

But as soon as I want to make "name" a variable, so I can interchange this using a function later on, it seems to stop working. For some reason, it always seems to return false.

const id = $("#div-1-name-1").attr("id");
const variableName = "name";
const regex = new RegExp(`/^div-\d-${variableName}-\d$/`);

console.log(regex.test(id)); // returns false, where true expected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="div-1-name-1"></div>

Am I perhaps inserting the variable in a wrong way? I cannot seem to figure it out.

Abran
  • 75
  • 2
  • 8

1 Answers1

2

You need to escape the regex string and remove the/ from the start and the end like this:

new RegExp(`^div-\\d-${variableName}-\\d$`);

Or as Wiktor commented

new RegExp(String.raw`^div-\d-${variableName}-\d$`);
Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36