Strange spaces in javascript regex

I saw this weird regular expression in javascript.

string = "abababababababa";
string=string.replace(/ ?a ?/g,"X");
alert(string);  

I ran it, and the result that I got was replaced with X. What causes bewilderment are spaces in the regular expression. I delete the first empty space, the script will not work. I delete the second empty space, I get one "a" replaced by two "X". I wonder how it works.

+4
source share
3 answers

Space actually means a white space match (U + 0020).

? quantifier, , "0 1 " , .

, / ?a ?/ :

  • "a"
  • "a "
  • " a"
  • " a "

:

  • (/?a ?/g) SyntaxError, - .

  • (/ ?a?/g) , ? a, :

    • ""
    • "a"
    • " "
    • " a"
+9

? .

, X .

> "a"
> " a"
> " a "
> "a "

.

+4

' ' . ? 1 0 .

:

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

:

  • 'a'
  • 'a '
  • ' a'
  • ' a '

a b a b a b a b a b a b a b a g (global ). ( )

  • , , .

  • If you leave a space character but delete the first one ?, it will be disabled because it looks like a space character, however, a space does not exist at the input.

  • If you delete the second space character, it still manages to combine awith the option.
+4
source

All Articles