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.
var re1 = new RegExp("abc");
var re2 = /abc/;
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) |
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. |
const re = /(\w+)\s(\w+)/;
let str = 'John Smith';
const newstr = str.replace(re, '$2, $1');
console.log(newstr);