Fatas
Fatas

Reputation: 295

JavaScript paste text to contenteditable with remove format

I want paste text to:

<div class="text" contenteditable="true"></div>

Then after paste i need that text will be with removed text formatting, but keep new lines.

I have this text this:

$(".text").bind({
    paste: function () {
        setTimeout(function () {
            var text = $(".text").text();
            $('.text').text(text);
        }, 100);
    }
});

But it's not add new lines;

Upvotes: 3

Views: 2415

Answers (1)

Fatas
Fatas

Reputation: 295

I've found out what I needed. This code does my required job:

$(".text").bind({
        paste: function () {
            setTimeout(function () {
                var text = $(".text").html();

                text = text.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '<br><br>');
                text = text.replace(/<div[^>]*>/g, '').replace(/<\/p>/g, '<br><br>');

                $('.text').html(text);

                $(".text *").not("br").each(function() {
                    var content = $(this).contents();
                    $(this).replaceWith(content);
                });

            }, 1);
        }
    });

Upvotes: 5

Related Questions