Чтобы разделить строку в JavaScript с помощью регулярного выражения, вы можете использовать метод split(). Вот несколько примеров:
-
Разделение по определенному символу:
const string = "Hello,World!"; const parts = string.split(","); // Splits the string at the comma console.log(parts); // Output: ["Hello", "World!"] -
Разделение по нескольким символам:
const string = "Hello-World!"; const parts = string.split(/[-!]/); // Splits the string at hyphen or exclamation mark console.log(parts); // Output: ["Hello", "World"] -
Разделение с помощью групп захвата:
const string = "Hello, World!"; const parts = string.split(/(, )/); // Splits the string while preserving the delimiter console.log(parts); // Output: ["Hello", ", ", "World!"] -
Разделение с лимитом:
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"]