| |

VerySource

 Forgot password?
 Register
Search
View: 829|Reply: 4

Problems with the identification of javascript regular expressions

[Copy link]

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-1-10 13:40:01
| Show all posts |Read mode
<script language = "javascript">
var Re = / [0-9] /;
document.write (Re.test ("0"));
document.write (Re.test ("0"));
document.write (Re.test ("0"));
</ script>

The result is true true true;

and
<script language = "javascript">
var Re = / [0-9] / g;
document.write (Re.test ("0"));
document.write (Re.test ("0"));
document.write (Re.test ("0"));
</ script>
The result is true false true.

One [g] difference, why is this happening?

Thank you!
Reply

Use magic Report

0

Threads

3

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

Post time: 2020-1-13 17:27:01
| Show all posts
This result may be related to test. Each time test and exec are executed, it moves the search in the string. There is a lastindex property, which is set to the character position of the matching substring. When test is called again, the matching will be performed from lastIndex. Therefore the first test it found has a '0', so it displays 'true'. When it is used the second time, it starts from the previous position, so if it is not found, it returns 'false'. So the return is 'true'.

Without [g], test and exec will always set lastIndex to 0.
Reply

Use magic Report

1

Threads

7

Posts

8.00

Credits

Newbie

Rank: 1

Credits
8.00

 China

Post time: 2020-2-14 23:15:01
| Show all posts
Will it happen?
Reply

Use magic Report

0

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-2-15 12:30:01
| Show all posts
g is global match
When a character is globally matched once, it will not be used next time
<script language = "javascript">
var Re = / [0-9] / g;
document.write (Re.test ("01"));
document.write (Re.test ("01"));
document.write (Re.test ("01"));
</ script>
Without g
Then it will match from scratch every time
So it is true every time
Reply

Use magic Report

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

 Author| Post time: 2020-3-5 16:15:02
| Show all posts
3Q
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list