Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - How to detect line breaks in a text area input?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(/
/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;

/ /g is a regular expression meaning 'look for the character (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...