Click here to Skip to main content
14,870,621 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add variables in regex, so i can update the regex frequently in function call depending on the parameters.

What I have tried:

JavaScript
let regex = '/year B.Tech sem Sem/g';
let year = 'II';
let sem = 'I';
regex = regex.replace('year',year);
regex = regex.replace('sem',sem);
console.log(regex)
// here the output is = /II B.Tech I Sem/g
regex = new RegExp(regex);
console.log(regex)
// here the regex changes and the output = /\/II B.Tech I Sem\/g/
Posted
Updated 10-Mar-21 3:51am
v2
Comments
NotTodayYo 9-Mar-21 14:22pm
   
OK, where are you stuck?

You're already using variables.

1 solution

Simple:
JavaScript
let year = 'II';
let sem = 'I';
let regex = new RegExp(`${year} B.Tech ${sem} Sem`, "g");
You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.

RegExp - JavaScript | MDN[^]
Template literals (Template strings) - JavaScript | MDN[^]
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900