Heil Programmierung
Heil Programmierung

Reputation: 187

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:

<ul>
 <li>der<li>
 <li>beste<li>
 <li>Mensch<li>
</ul>

So the general output should be:

Du bist

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.

Upvotes: 0

Views: 47

Answers (1)

Hao Wu
Hao Wu

Reputation: 20867

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>`
);

console.log(result);

Upvotes: 2

Related Questions