How to split long text inserted in <textarea> into paragraphs in <div> using any magic?

I have a div, a textareaand a button.

If I click button, any text inside will textareamove to divmixed as a very long text (unreadable).

I want, when I press Go button, the text will go to div, but split by paragraphsabout 200 characters -

PLEASE NOTE: Divide by the 200th Char , if it is a period or a full stop (.), if you do not look for the next period after the 200th Character .....

How can this be achieved?

Any suggestion or help is appreciated.

To get started, see my script: http://jsfiddle.net/zdCyq/

+4
source share
2 answers

Here is my solution:

function makeParagraphs(text){
    return '<p>' + text.replace(/(.{200}[^\.]*)(\.)+/g, '</p>$1.<p>') + '</p>';
}

You can test it in your example in jsfiddle .

+3
source

You can capture the text and skip it until you reach the end. Here is a Demo Screenshot

$(function () {
    $('button').on('click', function () {
        var theText = $('textarea').val();
        var i = 200;
        while (theText.length > 200) {
            console.log('looping');
            while (theText.charAt(i) !== '.') {
                i++;   
            }

            console.log(i);
            $("#text_land").append("<p>" + theText.substring(0, i+1) + "</p>");
            theText = theText.substring(i+1);
            i = 200;
        }

        $('#text_land').append("<p>" + theText + "</p>");
    })
})
+2
source

Source: https://habr.com/ru/post/1523363/


All Articles