0

Can someone explain me why the the following 2 the same Regular Expressions return different results when you run it "static" or dynamical? Should I add some escape character?

let arr = []
let re = /(\w+)\s(\w+)/
let str = 'John Smith'
let newstr = str.replace(re, '$2, $1')
arr.push(newstr) 

let code=`
   let re = /(\w+)\s(\w+)/
   let str = 'John Smith'
   let newstr = str.replace(re, '$2, $1')
   newstr
`
arr.push(eval(code))
arr

Output:

[
"Smith, John", 
"John Smith"
]
robert
  • 1,921
  • 2
  • 17
  • 27

1 Answers1

1

Exactly, you have to escape the baskslashes

const arr = [];
const re = /(\w+)\s(\w+)/;
const str = 'John Smith';
const newstr = str.replace(re, '$2, $1');

arr.push(newstr) ;

const code=`
   const re = /(\\w+)\\s(\\w+)/;
   const str = 'John Smith';
   const newstr = str.replace(re, '$2, $1');
   newstr;
`
arr.push(eval(code));

console.log(arr);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69