DEV Community

Margaret W.N
Margaret W.N

Posted on • Updated on

Regular expressions, Eloquent Javascript

Regular expressions are a way to describe patterns in string data
~Marijn Haverbeke

Declaring regular expressions.

Using RegExp():

let exp1 = new RegExp("xyz");
Enter fullscreen mode Exit fullscreen mode

Using a forward-slash:

let exp2 = /xyz/;
Enter fullscreen mode Exit fullscreen mode

Character groups

\d digit character
\w alphanumeric character
\s whitespace character
\DA character that is not a digit
\WA nonalphanumeric character
\SA non-whitespace character
. Any character except for a newline

Characters and their use in regular expressions

+ indicates that the element may be repeated more than once
* indicates that the element may be repeated more than once or omitted.
You have to use parenthesis in an expression that uses + or * more than once
{n} defines the number of times a pattern should occur. You can specify a range such as:

  • {3} - should occur exactly 3 times
  • {1, 3} - should occur at least once and at most thrice
  • {3,} - should occur at least three or times

- indicates a range of characters.
^ matches the start of the input string
$ matches the end of the input string
| used to define a choice of two expressions

To include some characters in a regular expression such as + you have to include a backslash.

let exp2 = /\+/;
Enter fullscreen mode Exit fullscreen mode

Regular expression Methods.

exec returns a match if found or null if no match is found. The value returned has an index property that indicates the position where the match was found.
test returns a boolean indicating whether the string contains the pattern.

Day 82 Done and dusted

Top comments (2)

Collapse
 
mcastellin profile image
Manuel Castellin

Mastering Regex is the one thing that you never have time to learn but you need every day..
Keep up the good work, Margaret!

Collapse
 
mtee profile image
Margaret W.N

It is indeed.

Thank you.