4

I want to remove rich text from my contenteditable div keep only newline or br tags when paste something from clipboard.

I'm trying but its doesn't work http://jsfiddle.net/marco83/zkf5jkqu/

<div id="editableDiv" contentEditable="true" style="min-height: 200px; border: solid 1px #0099FF;"></div>

<input type="button" value="remove" onclick="strip();">

<script>
function strip() {
    var mydiv = document.getElementById("editableDiv");
    var str  = mydiv.innerHTML;
    str = str.replace(/<br>/gi, "\n");
    str = str.replace(/<(?:.|\s)*?>/g, "");
    mydiv.innerHTML = str;
}
</script>

I copy the text from this page http://www.jacklmoore.com/autosize/
I know it doesn't have any <br> tag the text. but how can i do like Twitter does like this? Thanks.

enter image description here

1 Answer 1

5

Try This

<script>
    function strip() {
        var mydiv = document.getElementById("editableDiv");
        var str = mydiv.innerHTML;
        mydiv.innerHTML = remove_tags(str);
    }


    function remove_tags(html) {
        html = html.replace(/<br>/g, "$br$");
        html = html.replace(/(?:\r\n|\r|\n)/g, '$br$');
        var tmp = document.createElement("DIV");
        tmp.innerHTML = html;
        html = tmp.textContent || tmp.innerText;
        html = html.replace(/\$br\$/g, "<br>");
        return html;
    }
</script>

Example Here

So what i am doing is, i am replace <br> and \n with a placeholder $br$ so as to preserve them and then i am removing all the HTML tags from the string and replacing $br$ back with <br>

Sign up to request clarification or add additional context in comments.

1 Comment

That is like a temporary storage to preserve the <br> and \n

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.