Renato Ramos
Renato Ramos

Reputation: 429

jQuery I can't remove div tags when I paste text

My code removes all html tags except .

I need to paste plain text.

My HTM, where I paste the content:

<p contenteditable="true">A high altitude hike which offers incredible views of Aconcagua (6958m) and Tupungato (6427m) in Argentina.</p>

My jQuery code:

$('[contenteditable]').on('paste', function(e) {
                e.preventDefault();

                var text = '';

                if (e.clipboardData || e.originalEvent.clipboardData) {
                    text = (e.originalEvent || e).clipboardData.getData('text/plain');
                } else if (window.clipboardData) {
                    text = window.clipboardData.getData('Text');
                }


                if (document.queryCommandSupported('insertText')) {
                    document.execCommand('insertText', false, text);
                } else {
                    document.execCommand('paste', false, text);
                }
            });

My jsFiddle:

https://jsfiddle.net/ovnx27pg/

Upvotes: 1

Views: 771

Answers (2)

suresh bambhaniya
suresh bambhaniya

Reputation: 1687

You can use text.replace(/<[^>]*>?/gm, '');

$('[contenteditable]').on('paste', function(e) {

    e.preventDefault();

    var text = '';

    if (e.clipboardData || e.originalEvent.clipboardData) {
        text = (e.originalEvent || e).clipboardData.getData('text/plain');
    } else if (window.clipboardData) {
        text = window.clipboardData.getData('Text');
    }
    text = text.replace(/<[^>]*>?/gm, '');

    if (document.queryCommandSupported('insertText')) {
        document.execCommand('insertText', false, text);
    } else {
        document.execCommand('paste', false, text);
    }
    $(this).html($(this).html().replace(/<div>/gi,'<br>').replace(/<\/div>/gi,''));
});

$('[contenteditable]').keydown(function(e) {
    if (e.keyCode === 13) {
         document.execCommand('insertHTML', false, '<br><br>');
      return false;
    }
});

Upvotes: 1

Jaydeep Mor
Jaydeep Mor

Reputation: 1703

You just need to use text() that wrap HTML and return plain text from it.

$('[contenteditable]').on('paste', function(e) {
    e.preventDefault();

    var text = '';

    if (e.clipboardData || e.originalEvent.clipboardData) {
        text = (e.originalEvent || e).clipboardData.getData('text/plain');
    } else if (window.clipboardData) {
        text = window.clipboardData.getData('Text');
    }
    if (text) {
        text = $(text).text().trim();
    }

    if (document.queryCommandSupported('insertText')) {
        document.execCommand('insertText', false, text);
     } else {
        document.execCommand('paste', false, text);
     }
});

jsfiddle().

Upvotes: 1

Related Questions