0

I'm trying to create a regex in ES6, with a String Literal, but my solution fails :

var prefix = 'Hello';

var re = /`${prefix}\\s(\\w+)\\s(\\w+)`/;
//var re = /Hello\s(\w+)\s(\w+)/; // this works

var str = 'Hello John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);
colxi
  • 5,010
  • 1
  • 30
  • 36
user3552178
  • 1,693
  • 3
  • 20
  • 39
  • 3
    You can only use `${..}` in template literals. If you want to use a template literal, pass it to `new Regexp`. – CertainPerformance Aug 03 '18 at 03:01
  • 3
    why is this question being downvoted? It's fairly obvious what he's trying to achieve, and the solution is not trivial – Isaac Aug 03 '18 at 03:07
  • @Phil this question is **not a duplicate**, the referenced question uses variables, here string literals are used – colxi Aug 03 '18 at 03:33
  • @colxi I don't really think that constitutes a difference. Also, [one of the answers](https://stackoverflow.com/a/50828436/283366) uses string literals – Phil Aug 03 '18 at 05:05

1 Answers1

3

You need to use new RegExp

var prefix = 'Hello';
var reStr = `${prefix}\\s(\\w+)\\s(\\w+)`;
var re = new RegExp(reStr,'g')

var str = 'Hello John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);
colxi
  • 5,010
  • 1
  • 30
  • 36