59

What is the best way to check the text area value for line breaks and then calculate the number of occurrences, if any?

I have a text area on a form on my webpage. I am using JavaScript to grab the value of the text area and then checking its length.

Example

enteredText = textareaVariableName.val();
characterCount = enteredText.length; // One line break entered returns 1

If a user enters a line break in the text area my calculation above gives the line break a length of 1. However I need to give line breaks a length of 2. Therefore I need to check for line breaks and the number of occurrences and then add this onto the total length.

Example of what I want to achieve

enteredText = textareaVariableName.val();
characterCount = enteredText.length + numberOfLineBreaks;

My solution before asking this question was the following:

enteredText = textareaVariableName.val();
enteredTextEncoded = escape(enteredText);
linebreaks = enteredTextEncoded.match(/%0A/g);
(linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;

I could see that encoding the text and checking for %0A was a bit long-winded, so I was after some better solutions. Thank you for all the suggestions.

Community
  • 1
  • 1
Dave Haigh
  • 4,369
  • 5
  • 34
  • 56
  • 1
    @Dave Haigh, `Edit` is there for a reason , dont use `answer` section to add more details :) – Jashwant Jun 08 '12 at 14:45
  • @Jashwant it isn't extra details, it is an answer to my question... so I believe I have placed it in the right place. – Dave Haigh Jun 08 '12 at 14:47
  • If I am not wrong, "generally" your solution should be placed in answers section only when you want to mark as answer or if you discover an answer later. If you'll include your attempt in question, this will help others to look into your attempt. Finding your attempt in answers sections is little bit more difficult than finding it in your quesiton :) – Jashwant Jun 08 '12 at 14:55
  • 1
    @Jashwant may answer wasn't an attempt as it actually works. I purposely left it out of the question as I didn't want to influence any other answers. My question is pitched as 'how to' not 'is there a better way to'. There is nothing wrong with asking a question that you already have a working answer to too, in fact it is 'generally' encouraged. – Dave Haigh Jun 08 '12 at 15:00
  • Even if I take your points as right, there's nothing bad in adding that in your question. I think, you are tempered just because I edited your question. Also yes, it is encouraged but at [code review](http://codereview.stackexchange.com/) – Jashwant Jun 08 '12 at 15:07
  • 3
    I'm not tempered, I just disagree with you. – Dave Haigh Jun 08 '12 at 15:12

5 Answers5

81

You can use match on the string containing the line breaks, and the number of elements in that array should correspond to the number of line breaks.

enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;

/\n/g is a regular expression meaning 'look for the character \n (line break), and do it globally (across the whole string).

The ||[] part is just in case there are no line breaks. Match will return null, so we test the length of an empty array instead to avoid errors.

beeglebug
  • 3,522
  • 1
  • 23
  • 39
  • 3
    thanks for your answer, but I am curious what would be happened if user input `\n` by themselves? maybe they just wanna express this string. Is this way will replace the `\n` string to next line? – Chen-Tai Jun 23 '15 at 08:12
  • Yes it will. Javascript isn't really dependent on the OS, it only ever differs between browsers, and there is nothing in this answer which won't work all the way back to IE6. – beeglebug Jun 03 '16 at 10:38
4

Here's one way:

var count = text.length + text.replace(/[^\n]/g, '').length;

Alternatively, you could replace all the "naked" \n characters with \r\n and then use the overall length.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • this will double the counts for anything _except_ line breaks, and only for chars on the before the first line break. exactly the opposite of the OP's question, if I'm not mistaken. – Elias Van Ootegem Jun 08 '12 at 14:25
  • 2
    Elias: I think it's actually replacing everything that isn't a line break character with nothing, then counting the length of what's left, which will just be line breaks. Quite clever! – beeglebug Jun 08 '12 at 14:34
4

I'd do this using a regular expression:

var inTxt = document.getElementById('txtAreaId').value;
var charCount = inTxt.length + inTxt.match(/\n/gm).length;

where /\n/ matches linebreaks (obviously), g is the global flag. m stands for mult-line, which you evidently need in this case...
Alternatively, though as I recall this is a tad slower:

var charCount = inTxt.length + (inTxt.split("\n").length);

Edit Just realized that, if no line breaks are matched, this will spit an error, so best do:

charCount = intTxt.length + (inTxt.match(/\n/) !== null ? inTxt.match(/\n/gm).length : 0);

Or something similar...

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
3

You can split the text based on new lines:

let textArray = text.split(/^/gm)
console.log(textArray.length)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Anupam Chaplot
  • 1,134
  • 1
  • 9
  • 22
  • Thanks. This answer was helpful for finding the line breaks, while being able to keep the original text in the variable as well. – Maiya Jun 07 '21 at 17:34
2

For new JS use encodeURI(), because escape() is deprecated in ECMAScript 1.5.

Instead use:
enteredText = textareaVariableName.val(); enteredTextEncoded = encodeURI(enteredText); linebreaks = enteredTextEncoded.match(/%0A/g); (linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;

Peter
  • 373
  • 3
  • 10