-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.

1
  • 1
    just skip / chars Commented Jul 31, 2020 at 14:37

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.