Я не могу удалить теги Div, когда я вставляю текст - PullRequest
1 голос
/ 20 сентября 2019

Мой код удаляет все теги html, кроме.

Мне нужно вставить обычный текст.

Мой HTM, куда я вставляю содержимое:

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

Мой jQueryкод:

$('[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);
                }
            });

Мой jsFiddle:

https://jsfiddle.net/ovnx27pg/

Ответы [ 2 ]

1 голос
/ 20 сентября 2019

Вам просто нужно использовать text(), который переносит HTML и возвращать из него простой текст.

$('[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 () .

1 голос
/ 20 сентября 2019

Вы можете использовать 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;
    }
});
...