-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
  • 10,915
  • 5
  • 26
  • 67
Alan A
  • 2,443
  • 6
  • 30
  • 50

2 Answers2

0

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

DedaDev
  • 2,953
  • 1
  • 17
  • 24
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,323
  • 1
  • 10
  • 22