Если у вас мало времени, вот быстрый вариант:

  • регулярное выражение полезно в ряде случаев использования в Javascript
  • чтобы объявить регулярное выражение, которое НЕ является динамическим, нам просто нужно добавить «шаблон регулярного выражения» между двумя косыми чертами
  • вот так: пусть myRegex = /coding/ig (это говорит Javascript найти все вхождения слова «кодирование» в заданной строке)
  • но если мы заранее не знаем, какой шаблон мы сопоставляем, нам нужно использовать — new RegExp(‘\\w+’)

Если вы можете остаться подольше, читайте дальше.

Regex — это просто сопоставление с образцом.

Мы можем использовать регулярное выражение, чтобы найти слово «кодирование» в длинном фрагменте строки, например:

let myRegex = /coding/ig;

let myLongPieceOfString = "Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as analysis, generating algorithms, profiling algorithms' accuracy and resource consumption, and the implementation of algorithms (usually in a chosen programming language, commonly referred to as coding).";

let isMatch = myLongPieceOfString.match(myRegex); 

// try it yourself!!!

Ниже мы рассмотрим, как создать динамическое регулярное выражение для поиска шаблонов в фрагменте текста.

Когда нам нужно использовать динамические регулярные выражения?

Мы хотим сделать это, например, когда мы хотим перебрать элементы массива и попытаться найти соответствующие текстовые шаблоны для каждого элемента в фрагменте большего текста.

Давайте посмотрим на пример.

let arrayOfStrings = ['James', 'Bond', 'is', 'cool']; 

let largeText = "The James Bond series focuses on a fictional British Secret Service agent created in 1953 by writer Ian Fleming, who featured him in twelve novels and two short-story collections. Since Fleming's death in 1964, eight other authors have written authorised Bond novels or novelisations: Kingsley Amis, Christopher Wood, John Gardner, Raymond Benson, Sebastian Faulks, Jeffery Deaver, William Boyd, and Anthony Horowitz. The latest novel is With a Mind to Kill by Anthony Horowitz, published in May 2022. Additionally Charlie Higson wrote a series on a young James Bond, and Kate Westbrook wrote three novels based on the diaries of a recurring series character, Moneypenny.";

Здесь мы хотим найти совпадающие текстовые шаблоны каждого слова в arrayOfStrings в largeText.

как нам это сделать?

let arrayOfStrings = ['James', 'Bond', 'is', 'cool'];
let largeText = "The James Bond series focuses on a fictional British Secret Service agent created in 1953 by writer Ian Fleming, who featured him in twelve novels and two short-story collections. Since Fleming's death in 1964, eight other authors have written authorised Bond novels or novelisations: Kingsley Amis, Christopher Wood, John Gardner, Raymond Benson, Sebastian Faulks, Jeffery Deaver, William Boyd, and Anthony Horowitz. The latest novel is With a Mind to Kill by Anthony Horowitz, published in May 2022. Additionally Charlie Higson wrote a series on a young James Bond, and Kate Westbrook wrote three novels based on the diaries of a recurring series character, Moneypenny.";
    
    for(let word of arrayOfStrings) {
        console.log(`check word`, word);
        // create dynamic regex for each word
        // dynamic just means that each regex will be different for each word
        // remember to use backticks `` to use Template literals in Javascript
        let re = new RegExp(`${word}`, 'g');
        let isMatch = largeText.match(re); 
        if(isMatch) {
            console.log(`log matching word in text`, isMatch);
        } else {
            console.log(`no matching words found for ${word}`);
        }
    };

Подробнее о шаблонных литералах можно прочитать здесь.

Если вы запустите код в терминале или Visual Studio Code, вы должны увидеть в консоли следующее:

check word James
log matching word in text [ 'James', 'James' ]
check word Bond
log matching word in text [ 'Bond', 'Bond', 'Bond' ]
check word is
log matching word in text [
  'is', 'is',
  'is', 'is',
  'is', 'is',
  'is'
]
check word cool
no matching words found for cool

Вот и все. Надеюсь, вам понравился краткий урок.

Если вам нужна помощь в изучении Javascript или в прохождении собеседования по кодированию Javascript, вы можете связаться с нами по адресу [email protected]

Мы регулярно публикуем короткие технические руководства, поэтому рассмотрите возможность подписки на наш блог Medium.

До следующего раза — продолжайте программировать, продвигаясь небольшими шагами вперед в этом своем приключении.

Но что еще более важно, оставайтесь сосредоточенными!