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
The Mystery of the Disappearing Checkmarks
Force Download an Image Using JavaScript
Elliptic Curve Cryptography with Sjcl in Js and Openssl in Ruby
How to Pass Parameters in Get Requests with Jquery
Angular 2: Two Backend Service Calls on Success of First Service
How Should Look a Application.Scss File in Ruby
How to Detect When a Youtube Video Finishes Playing
Vue.Js - How to Properly Watch for Nested Data
How to Detect Emoji Using JavaScript
Ruby with Watir: Handling JavaScript Popup Window
Wicketpdf Rendering Table Not Aligned Properly and Footer Place at Last Page
How to Fix Ajax to Always Fire When Checking Box
Merge Keys Array and Values Array into an Object in JavaScript
How to Use JavaScript in Ruby on Rails
How to Scrape Data Using Ruby Which Is Generated by a JavaScript Function