How to detect line breaks in a text area input?

試著忘記壹切 提交于 2019-11-27 11:46:45

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.

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...

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.

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!