0

I'm searching this string for an the 'invite=XXXX' part. I am using a capturing group to extract the value between '=' and ';'. When I use the first regex method it works, but when I use the second it doesn't. Why is this?

var string = "path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; invite=1323969929057; path=/; expires=Sat, 14 Jan 2012 17:25:29 GMT;";

// first method
var regex1 = /invite=(\w+)/;
var regexMatch1 = string.match(regex1);

// second method
var regex2 = new RegExp("/invite=(\w+)/");  
var regexMatch2 = string.match(regex2);

// log results
console.log(regexMatch1);
console.log(regexMatch2);

Working example here >>

6 Answers 6

2

You have to escape the \ and like Jake said, remove the slashes.

var regex2 = new RegExp("invite=(\\w+)");  
                                  ^ Notice 2 "\"

http://jsfiddle.net/ZqkQ9/10/

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

1 Comment

That is still logging 'null' in my console (Chrome)
2

When you use the RegExp() constructor, the slashes are not needed. Change to this:

var regex2 = new RegExp("invite=(\\w+)"); 

1 Comment

You may also need to escape the backslash, as Daniel suggested
2

Because the / is for a regex literal. Since you are using the RegExp object, you need to remove the slashes. You also need to escape the backslash since you aren't using a literal:

var regex2 = new RegExp("invite=(\\w+)");  
var regexMatch2 = string.match(regex2);

Comments

2

It should be:

 var regex2 = new RegExp("invite=(\\w+)");  

Regular expressions in string form have no / prefix and postfix and all escape characters must have \\ instead of \.

Comments

1

You don't need the slashes while creating RegExp object using RegExp.

If you want, you can even compare the patterns using RegExp.source

Try console.log(regex1.source === regex2.source)

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

Comments

0

remove the /'s from the RegExp constructor, scape the \w and put the second parameter:

var regex2 = new RegExp("invite=(\\w+)", "");  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.