How to match the following string using regular expression in JavaScript?
I have got this pattern, [A-Z]{3}[0-9]{2}
, but seems that it's still missing something.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
3.6. (? i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
g is for global search. Meaning it'll match all occurrences. You'll usually also see i which means ignore case. Reference: global - JavaScript | MDN. The "g" flag indicates that the regular expression should be tested against all possible matches in a string.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
You also need anchors:
var regexp = /^[A-Z]{3}[0-9]{2}$/
Otherwise, substrings will also match (like ABC12
within xyzABC1234
).
^
means "start of string"$
means "end of 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