Template Literal Inside of the Regex

Template literal inside of the RegEx

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);

How do you use a template literal in a match RegEx?

There are a few issues with your code.

The first is that when you define a regex as a string, it doesn't require // marks, and also backslashes need to be double escaped \\d+.

The second is that num.toString().match(re) will return null if the regular expression doesn't match, thus you are getting an exception from trying to do an array lookup on null[0].

let truncateNum = (num, place = 2) => {
const matcher = `^-?\\d+(?:\\.\\d{0,${place}})?`; console.log(matcher);
const re = new RegExp(matcher);
const match = num.toString().match(re);
const result = match && match[0] || '0'
return result;
};

How do I use a template literal in a regular expression?

RegExp constructor might do the job if you need to build the regex dynamically, since it can also accept a string.

new RegExp(text, 'i');

Template Literals with Javascript Replace?

am I able to use template literals with javascript replace regex?

With regex literal (i.e., /^(.*)&/g) you can't. Template literals are meant to build strings, regex literals are not strings.

What you can do is use template literal to build the regex's pattern like bellow:

const regex = "~!@#$%^&*()_" ;
const data = "$88.10";
const pattern = `[^${regex}/gi]$`;
const result = data.replace(new RegExp(pattern, 'g'), '');

Alternatively you can create a Tagged template to build the regex for you like:

rgx`[${regex}]` // returns new RegExp('..

For example:

// tagged template functionfunction rgx(str0, str1){  return new RegExp(`${str0.raw[0]}${str1}${str0.raw[1]}`, 'gi')}
const regex = "~!@#$%^&*()_" ;const data = "$88.10";const result = data.replace(rgx`[${regex}]`, '');
console.log(result)

Capturing regex group inside of template literal as function argument

The $<day> named backreferences can only be used in string replacement patterns. Since you need to modify the captures, you need to use anonymous methods:

.replace(regex, (_,month,day,year) => `${pad(month)}`)

Here, in parentheses, you must define the variables for the whole match and for the capturing groups. So, basically, you need not the new ECMAScript 2018 regex enhancement since you can use regular numbered capturing groups here, too.

See the updated demo:

const pad = date => date.length === 2 ? date : '0' + date;
const normalizeDate = date => { const regex = /(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})/;
// pad string of length 1 works correctly (expected '01'/ result '01') console.log(date.replace(regex, (_,month,day,year) => pad(month)));
// pad sting of length 2 doesn't (expected '12' / result '012') console.log(date.replace(regex, (_,month,day,year) => pad(day)));
// test shows that <day> = 12 console.log(date.replace(regex, "$<day>"));
// padding 12 directly works (expected '12' / result '12') console.log(pad('12'));
return date.replace(regex, (_,month,day,year) => `${pad(month)}-${pad(day)}-${year}`);}
const date = '1/12/2014';console.log(normalizeDate(date));

Regex - capture tagged template literal

Regular Expression won't help you here, it is best to parse the JS file with an AST parser like @babel/parser - https://babeljs.io/docs/en/next/babel-parser.html

Template string from regex

Actually, I've found the path-to-regex that does exactly what I want.



Related Topics



Leave a reply



Submit