-1

I want to replace, in JavaScript, all lines that ends with semicolon ; with <li>$1</li>.

Example:

<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>

Would become:

<p>one</p>
<p>two</p>
<li>three</li>
<li>four</li>
<p>five</p>

(I don't have newlines, but <p>first</p><p>second</p>etc.)

I tried with this regex:

/<p>(.*?;)<\/p>/

but this match from the first <p>.

I would also like to wrap them in <ul></ul> but I think this is super advanced.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
user8980530
  • 43
  • 2
  • 6
  • 2
    Use a parser - [H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – ctwheels Mar 28 '18 at 19:26
  • Related -> https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – takendarkk Mar 28 '18 at 19:28

2 Answers2

0

No need for regex here, just loop over DOM elements and test whether or not they end in ;. If they do, slice it off!

var p = document.getElementsByTagName('p')
for (var i = 0; i < p.length; i++) {
  if(p[i].textContent.endsWith(';')) {
    var x = document.createElement('li')
    x.textContent = p[i].textContent.slice(0,-1)
    p[i].parentNode.insertBefore(x,p[i])
    p[i].parentNode.removeChild(p[i])
    i--
  }
}
<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>
ctwheels
  • 21,901
  • 9
  • 42
  • 77
0

Instead of using regular expressions, it would be better to simply use the appropriate DOM manipulation methods.
If you need older browser support, see this question on how to replace the for..of loop.

const nodes = document.querySelectorAll('p');
const matcher = new RegExp(';$');

for (const node of nodes) {
  if (!node.textContent.match(matcher)) continue;
  const newNode = document.createElement('li');
  newNode.textContent = node.textContent.replace(matcher, '');
  node.parentNode.replaceChild(newNode, node);
}
<p>one</p>
<p>two</p>
<p>three;</p>
<p>four;</p>
<p>five</p>
Etheryte
  • 24,589
  • 11
  • 71
  • 116