-1

I'm unable to parse a regex. I've tested it from regexpal.com and regex101.com (by setting the expression as "(?:^csrf-token|;\s*csrf-token)=(.*?)(?:;|$)" and the test string as "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj") where it works.

The example is jsfiddle.

function getCookie(name) {
			
    var s = "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj";
    
    var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
    var result = regexp.exec(s);
    return (result === null) ? null : result[1];
}
alert(getCookie("csrf-token"));

If however s is "csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", then it works fine. Please tell me what's wrong.

The expected output is "b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", and there is no input (the string to be tested is 's').

2
  • Can you please be a bit clearer about what your expected output is? Also, when you say you can't "parse a regex" do you mean that you can't create a regex that does what you want it to? Commented Dec 2, 2014 at 4:57
  • If you're creating a regex from a string you need to escape any backslashes in the string. So "\\s" not "\s". Commented Dec 2, 2014 at 5:02

2 Answers 2

2

Change

"|;\s*"

to

"|;\\s*"
    ^

The thing is, you are constructing the RegExp by passing in a string via the constructor, so you need to follow the rule of escaping in string literal. In JavaScript, "\s" is recognized as a single character string, with lowercase s. To specify \, you need to escape it.

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

Comments

2

You should escape \s

var regexp = new RegExp("(?:^" + "csrf-token" + "|;\\s*"+ "csrf-token" + ")=(.*?)(?:;|$)", "g");
                                                   ^

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.