JavaScript RegExp issue with lists

people! I have an issue where I don’t know how I can replace my text with ul, li tags.

Here it is: I have such text, for example:

let text = "Du bist der beste Mensch";

I need to convert the “der beste Mensch” part into:


So the general output should be:

Du bist

  • der
  • beste
  • Mensch

I tried to use regular expressions and ended up with:

text.replace(/(?:^|n)- (S+)/g, '<li>$1</li>');

If I put <ul><li>$1</li></ul>, it, of course, would give me those words boxed in both ul and li tags which is not what I wanted.


Assuming this is the format of the original text:

Du bist 
- der
- beste
- Mensch

You can nest the replace into 2 steps:

  1. Replace the entire list inside of <ul> tag
  2. Replace each list item inside of <li> tag

const text = `Du bist 
- der
- beste
- Mensch

const result = text.replace(/(?:(?:^|n+)- [^n]+)+/g, 
  list => `<ul>${list.replace(/(?:^|n+)- ([^n]+)/g, '<li>$1</li>')}</ul>`