Search code examples
javascriptreplacequill

replace repeating html-tags in javascript


I am using the quill.js editor to allow users to write comments. The problem with quill.js is, if they press enter, a new paraph is generated.

<p><br></p>

This allows them to create infinite new lines. For example the input:

fffff ffff fff
fff


fffffff



ff

would generate this html:

<p>fffff ffff fff</p>
<p>fff</p>
<p><br></p>
<p><br></p>
<p>fffffff</p>
<p><br></p>
<p><br></p>
<p><br></p>
<p>ff</p>

But I want to get a result like this:

<p>fffff ffff fff</p>
<p>fff</p>
<p><br></p>
<p>fffffff</p>
<p><br></p>
<p>ff</p>

so if the newline code is repeated, it should be replaced with a single new line. How do I do this?


Solution

  • You can check if there are two or more occurrences of the <p><br></p> followed by a new line and if so, you replace it with a single one like so:

    const markup = `
    <p>fffff ffff fff</p>
    <p>fff</p>
    <p><br></p>
    <p><br></p>
    <p>fffffff</p>
    <p><br></p>
    <p><br></p>
    <p><br></p>
    <p>ff</p>
    <p><br></p>
    `;
    
    const result = markup.replace(/(<p><br><\/p>\n){2,}/g, '<p><br><\/p>\n');
    
    console.log(result);

    You could even as far as:

    const markup = `
    <p>fffff ffff fff</p>
    <p>fff</p>
    <p><br></p>
    <p><br></p>
    <p>fffffff</p>
    <p><br></p>
    <p><br></p>
    <p><br></p>
    <p>ff</p>
    <p><br></p>
    `;
    
    const target = '<p><br><\/p>\n';
    
    const result = markup.replace(new RegExp(`(${target}){2,}`, 'g'), target);
    
    console.log(result);

    So you can change the element easily in the future.