RegExp

const regex1 = /\w+/;
const regex2 = new RegExp('\\w+');

console.log(regex1);
// Expected output: /\w+/

console.log(regex2);
// Expected output: /\w+/

console.log(regex1 === regex2);
// Expected output: false

RegExp.prototype.compile() ЗАСТАРІЛЕ!

(Пере-) компілює регулярний вираз під час виконання сценарію.

RegExp.prototype.exec()

Виконує пошук відповідності в параметрі рядка.

RegExp.prototype.test()

Перевіряє збіг у своєму рядковому параметрі.

RegExp.prototype.toString()

Повертає рядок, що представляє вказаний об’єкт. Перевизначає Object.prototype.toString() method.

RegExp.prototype[@@match]()

Виконує зіставлення з заданим рядком і повертає результат збігу.

RegExp.prototype[@@matchAll]()

Повертає всі збіги регулярного виразу з рядком.

RegExp.prototype[@@replace]()

Замінює збіги в заданому рядку новим підрядком.

RegExp.prototype[@@search]()

Шукає відповідність у заданому рядку та повертає індекс шаблону, знайденого в рядку.

RegExp.prototype[@@split]()

Розділяє заданий рядок на масив шляхом поділу рядка на підрядки.

The following script uses the String.prototype.replace() method to match a name in the format first last and output it in the format last, first.

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

const re = /(\w+)\s(\w+)/;
const str = "Maria Cruz";
const newstr = str.replace(re, "$2, $1");
console.log(newstr);

This displays "Cruz, Maria".

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

const text = "Some text\nAnd some more\r\nAnd yet\rThis is the end";
const lines = text.split(/\r\n|\r|\n/);
console.log(lines); // [ 'Some text', 'And some more', 'And yet', 'This is the end' ]

Note that the order of the patterns in the regular expression matters.

const s = "Please yes\nmake my day!";

s.match(/yes.*day/);
// Returns null

s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

const str = "#foo#";
const regex = /foo/y;

regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex is taken into account with sticky flag)
regex.lastIndex; // 0 (reset after match failure)

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

const re = /\d/y;
let r;
while ((r = re.exec("123 456"))) {
  console.log(r, "AND re.lastIndex", re.lastIndex);
}

// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
//  … and no more match.

With the global flag g, all 6 digits would be matched, not just 3.

\w and \W only matches ASCII based characters; for example, a to z, A to Z, 0 to 9, and _.

To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where hhhh is the character's Unicode value in hexadecimal.

This example demonstrates how one can separate out Unicode characters from a word.

JSCopy to Clipboard

const text = "Образец text на русском языке";
const regex = /[\u0400-\u04FF]+/g;

const match = regex.exec(text);
console.log(match[0]); // 'Образец'
console.log(regex.lastIndex); // 7

const match2 = regex.exec(text);
console.log(match2[0]); // 'на' (did not log 'text')
console.log(regex.lastIndex); // 15

// and so on

The Unicode property escapes feature provides a simpler way to target particular Unicode ranges, by allowing for statements like \p{scx=Cyrl} (to match any Cyrillic letter), or \p{L}/u (to match a letter from any language).

const url = "http://xxx.domain.com";
console.log(/^https?:\/\/(.+?)\./.exec(url)[1]); // 'xxx'

Note: Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";

order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']

Last updated