How can i match a markdown list text block via javascript regex?

Viewed 697

Hey Stack Overflow members, I am trying to parse this text and get two separate matches, the unordered markdown list blocks. The problem is that i cannot figure out a way to match them. There maybe text after them.

I am using JavaScript flavored regex.

This is what i have been trying, full example: Regex101

(\*|\t\*|\s+\*).*

List:

* Item 1
* Item 2
    * Item 2a
    * Item 2b

* Item 1
* Item 2
    * Item 2a
    * Item 2b

Thank you in advance for your help.

1 Answers

[\s\S] will make JavaScript multiline, since dot . doesn't do multiline.

[\s\S] will search for every whitespace and non-whitespace character including newline characters.

var match = document.querySelector("pre").textContent.match(/(\*|\t\*|\s+\*)[\s\S]*?\n\n/g);

console.log(match);
<pre>

When there is text preceding the block

* Item 1
* Item 2
    * Item 2a
    * Item 2b

* Item 1
* Item 2
    * Item 2a
    * Item 2b
    
When there is more text in the block
</pre>

Another method. Use the global flag g for your match.

var match = document.querySelector("pre").textContent.match(/(\*|\t\*|\s+\*).*/g);

//raw match
console.log(match);

//with trim
match_trim = match.map(function(element){
    return (element.trim());
});

console.log(match_trim);

//with join
match_join = match.join("");

console.log(match_join);
<pre>
* Item 1
* Item 2
    * Item 2a
    * Item 2b

* Item 1
* Item 2
    * Item 2a
    * Item 2b
</pre>

Related