I saw this weird regex in javascript.
string = "abababababababa";
string=string.replace(/ ?a ?/g,"X");
alert(string);
I ran it , and the output I got was all a replaced by X What is puzzling is the white spaces in the regex. I delete the first white space, the script won't run. I delete the 2nd white space, I get one "a" replaced by two "X"s. I wonder how it works.
The space actually means to match a space character (U+0020).
The key is the ?
quantifier that follows each of them, allowing the pattern to match "0 or 1 spaces" for each, essentially making them optional.
So, the / ?a ?/
pattern is capable of matching:
"a"
"a "
" a"
" a "
And, attempting to remove either space will change the meaning of the pattern:
Removing the leading space (/?a ?/g
) actually results in a SyntaxError
as quantifiers require something before them to quantify.
Removing the trailing space (/ ?a?/g
) is syntactically valid, but the ?
quantifier will then apply to the a
, changing the possible matches to:
""
"a"
" "
" a"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With