Home > front end >  In the resolution of the regular expression, why its a bit strange...
In the resolution of the regular expression, why its a bit strange...

Time:11-16



So write words, parsing is an error on the chrome,
Regular test site, but in some online can be a match,,, how to rewrite, to make the code on the graph matching success in chrome?
 
Var kk='? S=55 & amp; T=88 '
Var reg=new RegExp (" (^ | \? | & amp;) S=(. *) [& amp; $] ")
Var s=kk. Match (reg)
The console. The log (s)

CodePudding user response:

""?" The string is said?
"\ "?" Or "\ \ \?" Said is the string \?
Reason is that the string "" said the backslash will be escaped

CodePudding user response:

Because the new RegExp (" (^ | \? | & amp;) S=(. *) [& amp; $] ") is to define a string first, and then use this string to create a regular expression object,
When defining a string, js source code defined in the "(^ | \? | & amp;) S=(. *) [& amp; $] "is a string literal, \ and escape character in the string literals,
Such as \ n will escape into a newline, and is not in the actual string generated \ this character,
The same \? Will escape into? , is not in the actual string generated \ this character,
To appear in the resulting string fact \ characters, need written in string literals \ \
So need to write new RegExp (" (^ | \ \? | & amp;) S=(. *) [& amp; $] ")

Note that the string literal and the difference between the actual string,

Can be in the regular testing site, because it is direct access to the value of the actual string in the text box, is not defined in js source string literals, \ won't escape,

In addition, also can use/(^ | \? | & amp;) S=(. *) [& amp; $]/regular expressions literal, create a regular expression object directly, without a string literal, \ won't escaped,
  • Related