I am writing a JS parser, and am wondering how to differentiate between a regular expression (/lookup/g
) and simple division (bar/baz/g
). What are the rules that JavaScript uses to identify regular expressions?
Regular expressions are a sequence of characters that are used for matching character combinations in strings for text matching/searching. In JavaScript, regular expressions are search patterns (JavaScript objects) from sequences of characters. RegExp makes searching and matching of strings easier and faster.
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.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
You want to check out Section 7.8.5 in the ECMA spec (the annotated version is up-to-date currently, but always check the latest PDF from the ECMA).
Remember too that a JavaScript regex can not be empty. //
is always the start of a single line comment. It's also worth mentioning that a semicolon must never be inserted before a regex literal.
Tangential, an empty JavaScript regex looks like /(?:)/
.
Further discussion.
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