Search code examples
javascripthtmlcontenteditable

Javascript: How to trim an editable div content


I have an editable div in which users write text for comment. Now I want to remove space before and after the text. For example when a user type

"  Hello world   "

I have to insert

"Hello world" 

into the database.

I have tried

text.trim()

but it doesn't work. How can I do this ?

Also how to remove duplicates empty line ?

I would like to replace

<div>Hello</div>
<div></div>
<div></div>
<div></div>
<div>World</div>

By

<div>Hello<div>
<div></div>
<div>World</div>

Thank you


Solution

  • you will need to remove <br> and <div> not empty strings . Please see below:

    function trimDiv(){
    
    
    
    var text = document.getElementById("test").innerHTML.replace(/&nbsp;/gi, '').replace(/<div><br><\/div>/gi, '').replace(/<p><br><\/p>/gi, '');
    
    //.replace(/<\/div>/gi, '');
    
    document.getElementById("test").innerHTML=text;
    }
    <div id="test" contenteditable>   Hello World   </div>
    
    <button id="trimText" onclick="trimDiv();">Trim</button>

    Edit: Now code snipped will keep one Enter out of many repeated. Edit 2: Works in IE as well Try again