Regular Expression in Javascript
Regular Expression in Javascript
Javascript
JavaScript Regex
/^a...s$/
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and
ending with s.
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine.
[] . ^ $ * + ? {} () \ |
[] - Square brackets- specify a set of characters we wish to match
Also specify a range of characters using - inside square brackets.
[a-e] is the same as [abcde].
[1-4] is the same as [1234].
[0-39] is the same as [01239].
Complement (invert) the character set by using caret ^ symbol at the start of a square-bracket.
The caret symbol ^ is used to check if a string starts with a certain character.
A. var pattern = /^hello/;
console.log(pattern.test("hello world")); // Output: true
console.log(pattern.test("hi hello")); // Output: false
B. var pattern = /[^hello]/;
console.log(pattern.test("hello world")); // Output: false
$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.
* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.
The plus symbol + matches one or more occurrences of the pattern left to it.
? - Question Mark
The question mark symbol ? matches zero or one occurrence of the pattern left to it.
Matches the preceding element either zero or one time.
{} - Braces
Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it.
This RegEx [0-9]{2, 4} matches at least 2 digits but not
more than 4 digits.
| - Alternation
Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string
that matches either a or b or c followed by xz
\ - Backslash
Backslash \ is used to escape various characters including all metacharacters. For example,
\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a
special way.
Special Sequences
Special sequences make commonly used patterns easier to write. Here's a list of special sequences: