Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript detect regular expressions?

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?

like image 836
Azmisov Avatar asked Nov 30 '11 22:11

Azmisov


People also ask

How do regular expressions work in JavaScript?

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.

How do you check if a string is a regular expression JavaScript?

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.

How do I check if a string is in regular expressions?

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.


1 Answers

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.

like image 188
alex Avatar answered Oct 01 '22 14:10

alex