-1

Simple question how to use a variable in a javascript regular expression?

I tried:

var regex = new RegExp('/^' + name + '/');
var result = cookie.name.match(regex);

This does not work - if I debug the var regex I get:

/\/^foobar\//

For the record I am expecting to match a cookie named foobar_xxxxxxxx

Something so simple is somehow so challenging? I've seen numerous other posts asking the same question without a satisfactory answer that works in my case.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Alan A
  • 2,557
  • 6
  • 32
  • 54

2 Answers2

0

You don't need slashes for writing regex using RegExp function.

DedaDev
  • 4,441
  • 2
  • 21
  • 28
0

Removing the slashes worked for me. As new RegExp appends / while returning we don't need to specifically mention it. Check out this for reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

let name = 'foobar'
var regex = new RegExp('^' + name);
var result = 'foobar_xxxxxxxx'.match(regex);
Dinesh Nadimpalli
  • 1,441
  • 1
  • 13
  • 23