I have a string.
var string="ghtykj";
var pattern = "t*y";
When I give new RegExp(pattern).test(string), it returns true(as expected).
var pattern = "t*g";
But this pattern also returns true.
I was expecting this pattern to return false, since t*g means t followed by zero or more number of characters ,followed by g.
If this is indeed the expected behavior , could any one correct me where i am doing wrong?
The g flag indicates that the regular expression should be tested against all possible matches in a string.
The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).
The Global Flags (gflags.exe) utility provides a simple method of setting certain keys within the system registry, adjusting the kernel settings of the running system, and altering the settings for image files. You can set these keys by using a graphical or command-line interface.
The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched. This is required field.
The *
isn't a wildcard character in a regular expression, is a quantifier. It has the same meaning as the quantifier {0,}
, i.e. specifying that the expression before it (in this case the character t
) can occur zero or more times.
The pattern t*g
doesn't mean t followed by zero or more number of characters, followed by g. It means zero or more of the character t, followed by one g.
The pattern t*g
would match for example tg
or tttttg
, but also just g
. So, it matches the g
character at the beginning of the string.
To get a pattern that matches t followed by zero or more number of characters, followed by g you would use t.*g
(or t[\w\W]*g
to handle line breaks in the string).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With