How to divide long text pasted in the <textarea> into paragraphs in a <div> using any magic possible?

StackOverflow https://stackoverflow.com/questions/21311661

Domanda

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/

È stato utile?

Soluzione

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.

Altri suggerimenti

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>");
    })
})
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top