Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template literal inside of the RegEx

I tried to place a template literal inside of a RegEx, and it didn't work. I then made a variable regex which holds my RegEx, but it still not giving me the desired result.

However if I console.log(regex) individually, I do receive the desired RegEx, such as /.+?(?=location)/i, /.+?(?=date)/i and so on, but once I place regex inside the .replace it appears not to be working

function validate (data) {   let testArr = Object.keys(data);   errorMessages.forEach((elem, i) => {     const regex = `/.+?(?=${elem.value})/i`;     const a = testArr[i].replace(regex, '');     })   } 
like image 336
vlad Avatar asked Apr 13 '17 11:04

vlad


People also ask

What is a template literal?

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.

How do you use regex literals?

If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash. If you want to match 1+1=2, the correct regex is 1\+1=2. Otherwise, the plus sign has a special meaning. Note that 1+1=2, with the backslash omitted, is a valid regex.

Can you put a variable inside a regex?

It's not reeeeeally a thing. There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.


1 Answers

Your regex variable is a String. To make it a RegExp, use a RegExp constructor:

const regex = new RegExp(String.raw`pattern_as_in_regex_literal_without_delimiters`) 

For example, a regex literal like /<\d+>/g can be re-written as

const re = RegExp(String.raw`<\d+>`, 'g') // One \ is a literal backslash const re = RegExp(`<\\d+>`, 'g')       // Two \ are required in a non-raw string literal 

To insert a variable you may use

const digits = String.raw`\d+`; const re = RegExp(`<${digits}>`, 'g') 

To solve your issue, you may use

const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i");  

Also, it is a good idea to escape the variable part in the regex so as all special regex metacharacters were treated as literals.

const s = "final (location)"; const elemvalue = "(location)"; const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i"); // console.log(regex); // /.+?(?=\(location\))/i // console.log(typeof(regex)); // object let a = s.replace(regex, ''); console.log(a);
like image 148
Wiktor Stribiżew Avatar answered Sep 19 '22 13:09

Wiktor Stribiżew