weird white spaces in javascript regex

Viewed 542

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.

3 Answers
Related