Question: 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.

Answer: 
The space actually means to match a space character (U+0020).

The key is the [`?` quantifier](http://www.regular-expressions.info/optional.html) 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"`
`' '` is matching an actual space character. The `?` quantifier means **Match** `1` or `0` times.

Your regular expression does the following:

```
 ?          ' ' optional space character
a           match 'a'
 ?          ' ' optional space character

```

It will match the following cases:

* `'a'`
* `'a '`
* `' a'`
* `' a '`

You regular expression will match `a`b`a`b`a`b`a`b`a`b`a`b`a`b`a` in your input string using the `g` (global modifier). Meaning all matches (don't return on first match)

* If you remove the space character at the beginning the preceding token is not quantifiable so it will **fail**.
* If you leave the space character but remove the first `?` it will **fail** because it looks to match a space character, however a space character does not exist in the input.
* If you remove the second space character, it still succeeds the match making `a` optional here.