Alejo
Alejo

Reputation: 807

Paragraphs in javascript

Do you know if there is an easy way of counting paragraphs in a textarea using nothing but javascript?

Thanks,

Upvotes: 1

Views: 7430

Answers (4)

Aman Choudhary
Aman Choudhary

Reputation: 1

const countParagraphs = (text) =>{
  return text.split(/\n\s*\n/).filter(Boolean).length;
}

This function efficiently counts paragraphs in a text by splitting the text based on the presence of blank lines or indentation and then filtering out any empty paragraphs before returning the count.

Upvotes: 0

Sethias
Sethias

Reputation: 790

You can improve Sean Viera answer by splitting on (\n *\n)/g instead of just \n\n then you have no issues with spaces between the paragraphs

Upvotes: 0

Sean Vieira
Sean Vieira

Reputation: 159955

var my_data = document.getElementById("txt_area_in_question").value;
alert("The total paragraphs in the text area are: "+ 
                            my_data.split("\n\n").length)​;​​​

Now, this doesn't take into account multiple newlines without text ... so:

Some text

Some more text





Some more text

will return 5 rather than 3

The solution is to strip out all whitespace, and return what's left:

var my_data = document.getElementById("txt_area_in_question").value;
my_data = my_data.split("\n\n");
var g = my_data.length;
var i = 0;
var strip_whitespace = /\s+/gi;
while (g >=0) {
    g--;
    var tmp = my_data[g];
    tmp = tmp ? tmp .replace(strip_whitespace,"") : tmp;
    if( tmp && tmp.length > 1 ) {
        i++;
    }
}
alert("The total paragraphs in the text area are: "+i)​;​​​​ //Will properly alert 3

See: http://jsfiddle.net/UBWpJ/

Upvotes: 3

fantactuka
fantactuka

Reputation: 3334

Try this one:

document.getElementById('textarea_id').value.replace(/\n$/gm, '').split(/\n/).length;

This will ignore empty strings (see @Sean Vieira answer)

Upvotes: 6

Related Questions