Saturday, 1 April 2017

Javascript String to Regex without Escaping

I have a question regarding regular expressions in nodejs/javascript.

What I am trying to achieve is to convert a regex (loaded from a database as a string) without any escaping to a RegExp object in js.

var regex       = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = '/Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/';

var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';

var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);

That's what I tried so far. But as you can see it won't match if the string gets escaped... My output:

[ 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18',
  '2.2.9',
  'Debian',
  'PHP/5.2.6-1+lenny18',
  index: 0,
  input: 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18' ]
null

Am I missing something simple? If not any suggestions for me? Thanks



via Nightforce

No comments:

Post a Comment