Skip to content

Instantly share code, notes, and snippets.

@bigsergey
Last active September 22, 2022 00:49
Show Gist options
  • Save bigsergey/0db46263b37de893252608f39ae788e4 to your computer and use it in GitHub Desktop.
Save bigsergey/0db46263b37de893252608f39ae788e4 to your computer and use it in GitHub Desktop.

Regular expressions

Definition by MDN:

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions.

Creating a regular expression

var re1 = new RegExp("abc");
var re2 = /abc/;

Special characters

Character Meaning
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abc def)

Methods that use regular expressions

Method Description
exec A RegExp method that executes a search for a match in a string. It returns an array of information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

Example

const re = /(\w+)\s(\w+)/;
let str = 'John Smith';
const newstr = str.replace(re, '$2, $1');
console.log(newstr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment