Home  >  Q&A  >  body text

javascript - Regular expression to match multiple consecutive characters and replace them with one character

Regular expressions are rarely used, so I’m here to ask you for advice. . .

var reg=/<p><br><\/p><p><br><\/p><p><br><\/p>/;
var con=$('#content').html().replace(reg, '<p><br></p>');

That is, I want to match the consecutive /<p>
</p> into one, so as not to see all line breaks. Now, three reg matches are replaced with one p tag. This is problematic. . . . . . For example, if I have five p tags, he will output three p tags. . . Because after matching the first three, he will continue matching from the second p tag! Asking for help

怪我咯怪我咯2690 days ago712

reply all(3)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-18 11:04:12

    var str = '<p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p>'
    var reg=/<p>(<br>|<p>|<\/p>)*<br><\/p>/gi;
    console.log(str.replace(reg, '<p><br></p>'));

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 11:04:12

    var reg = /<p>|</p>/g;
    var con = $('#content').html().replace(reg, '');
    con = '<p>' + con + '</p>';

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 11:04:12

    var reg = /(<p><br><\/p>)(\1)+/g;
    var str = '<p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p>';
    alert(str.replace(reg,'$1'));

    reply
    0
  • Cancelreply