简体   繁体   中英

What exactly is this regular expression doing?

I'm looking over some code and found the following regex:

var querystring = querystring.replace(/[^&]+=\.?(?:&|$)/g, '')

Is this taking the querystring and replacing all values that begin with an ampersand or question mark with a space? Is there more going on here that I don't see?

You're logical explanation is much appreciated and help gain a little more understanding of regex. Thanks!

It appears to remove those parameters from the query string whose value is:

  1. empty
  2. equal to .

For example:

"remove1=&remove2=.&keep1=..&keep2=a&keep3=b".replace(/[^&]+=\.?(?:&|$)/g, '')
// returns "keep1=..&keep2=a&keep3=b"

[^&]+ one or more non "&" characters

= a literal "=" character

\\.? an optional "."

(?:&|$) a "&" character or the end of the string

Would eg match

Foobar=.&
A=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM