文章目录
  1. 1. Defined
  2. 2. Main()
  3. 3. Reference

Defined

Came across RegExp Object prob when tring to learning template engine writing.

Main()

From the refer link
I recommend that you do not use the RegExp constructor with a literal string, because in literal strings, backslashes must be escaped. The regular expression \w+ can be created as re = /\w+/ or as re = new RegExp("\\w+"). The latter is definitely harder to read. The regular expression \\ matches a single backslash. In JavaScript, this becomes re = /\\/or re = new RegExp("\\\\").

and the demo code is:

1
2
3
4
let template = 'My age is <span>${age}</span></p>';
console.log(template.replace(/\${age}/, 22)); // It works
console.log(template.replace(new RegExp('\${age}', 'g'), 22)); // Not worked
console.log(template.replace(new RegExp('\\${age}', 'g'), 22)); // It works

PS: I just came across this prob a moment before, but I can remember it today, so Record it.

Reference

regular-expressions

文章目录
  1. 1. Defined
  2. 2. Main()
  3. 3. Reference