Разделение строк JavaScript с использованием регулярных выражений: методы и примеры

Чтобы разделить строку в JavaScript с помощью регулярного выражения, вы можете использовать метод split(). Вот несколько примеров:

  1. Разделение по определенному символу:

    const string = "Hello,World!";
    const parts = string.split(","); // Splits the string at the comma
    console.log(parts); // Output: ["Hello", "World!"]
  2. Разделение по нескольким символам:

    const string = "Hello-World!";
    const parts = string.split(/[-!]/); // Splits the string at hyphen or exclamation mark
    console.log(parts); // Output: ["Hello", "World"]
  3. Разделение с помощью групп захвата:

    const string = "Hello, World!";
    const parts = string.split(/(, )/); // Splits the string while preserving the delimiter
    console.log(parts); // Output: ["Hello", ", ", "World!"]
  4. Разделение с лимитом:

    const string = "Hello, World, How, Are, You";
    const parts = string.split(", ", 3); // Splits the string at each comma, limiting to three parts
    console.log(parts); // Output: ["Hello", "World", "How"]