Parsing regex in javascript -
this question has answer here:
- javascript regex, use escape characters? 3 answers
i'm unable parse regex. i've tested regexpal.com , regex101.com (by setting expression "(?:^csrf-token|;\s*csrf-token)=(.*?)(?:;|$)"
, test string "__ngdebug=false; csrf-token=b2ssoj4jnolpdmxahn4corpvfoo4ngsupej25tdj") works.
the example 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 s
"csrf-token=b2ssoj4jnolpdmxahn4corpvfoo4ngsupej25tdj"
, works fine. please tell me what's wrong.
the expected output "b2ssoj4jnolpdmxahn4corpvfoo4ngsupej25tdj"
, , there no input (the string tested 's').
change
"|;\s*"
to
"|;\\s*" ^
the thing is, constructing regexp passing in string via constructor, need follow rule of escaping in string literal. in javascript, "\s"
recognized single character string, lowercase s
. specify \
, need escape it.
Comments
Post a Comment