Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird white spaces in javascript regex

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.

like image 733
Flmhdfj Avatar asked Dec 02 '22 21:12

Flmhdfj


1 Answers

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"
like image 181
Jonathan Lonowski Avatar answered Dec 12 '22 01:12

Jonathan Lonowski