Skip to content
Advertisement

Javascript: Regex to convert a numbered list string to an array of items

I am trying to convert a numbered list into an array of items. This is what I have so far:

let input = `1. This is a textn    where each item can span over multiple linesn  1.1 this is another itemn 1.2another itemn  2. that I want ton    extract each seperaten    item fromn    3. How can I do that?`;

let regex = /(d+.d+|d+)s(.*)/g;
let matches = input.match(regex);
console.log(matches);

This only produces the following output:

"1.1 this is another item"

What I would like is something like this:

"1. This is a text"
"1.1 this is another item"
"1.2another item"
...and so on

Why is it matching only one item out of this string? What am I doing wrong and how can I fix it?

Advertisement

Answer

Your regex does not foresee a dot after a number when there is no second number following it. It also requires a space after the number, but you have a case where there is no such space. So make it optional.

Also, use the s modified so . also matches newline cha

If a new item can start on the same line, you’ll need a look-ahead to foresee where a match must end.

Correction:

let input = `1. This is a textn    where each item can span over multiple linesn  1.1 this is another itemn 1.2another itemn  2. that I want ton    extract each seperaten    item fromn    3. How can I do that?`;

let regex = /(d+.d*)s?(.*?)(?=d+.|$)/gs;
let matches = input.match(regex);
console.log(matches);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement