如何检测文本区输入中的换行符? [英] How to detect line breaks in a text area input?

查看:266
本文介绍了如何检测文本区输入中的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查换行符的文本区域值然后计算出现次数的最佳方法是什么?

我的网页上的表单上有一个文本区域。我使用JavaScript来获取文本区域的值,然后检查其长度。

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.

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

如果用户在文本区域输入换行符,我的计算结果上面给出了换行符的长度1.然而,我需要给出换行符的长度为2.因此我需要检查换行符和出现次数,然后将其添加到总长度上。

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.

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;

我可以看到编码文本并检查%0A 有点啰嗦,所以我找到了一些更好的解决方案。感谢您提出的所有建议。

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.

推荐答案

您可以使用匹配包含换行符的字符串,该数组中元素的数量应与换行符的数量相对应。

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 是一个正则表达式意思是查找字符 \ n (换行符),并在全局(整个字符串)中执行。

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

|| [] 部分是为了防万一没有换行符。匹配将返回 null ,因此我们测试空数组的长度,以避免错误。

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.

这篇关于如何检测文本区输入中的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆