Reputation: 187
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
Reputation: 20867
Assuming this is the format of the original text:
Du bist
- der
- beste
- Mensch
You can nest the replace
into 2 steps:
<ul>
tag<li>
tagconst 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