Question

I got a div, a textarea, and a button.

If I click the button, any text inside the textarea will go to the div mixed as a very long text (unreadable).

What I want is, when I click the Go button, the text would go to the div but split into paragraphs of about 200Characters-

PLEASE NOTE: Split at 200th Char if it's a period or Full-Stop(.) if not look for the next period after the 200th Character.....

How can this be achieved?

Any Suggestion or help is highly appreciated.

To start with, Please see my Fiddle: http://jsfiddle.net/zdCyq/

Was it helpful?

Solution

Here's my solution to this:

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

You can test it in your example in this jsfiddle.

OTHER TIPS

You can grab the text and loop through all of it until you get to the end. Here is a Fiddle Demo

$(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>");
    })
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top