So, I have to get HTML of textarea and check whether it contains line break. How can i see whether it contain \n
because the string return using val()
does not contain \n
and i am not able to detect it. I tried using .split("\n")
but it gave the same result. How can it be done ?
One minute, IDK why when i add \n
to textarea as value, it breaks and move to next line.
Create a string containing line breaksInserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.
Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format. If it is a Windows EOL encoded file, the newline characters of CR LF will appear (\r\n). If the file is UNIX or Mac EOL encoded, then it will only show LF (\n).
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
Line breaks in HTML aren't represented by \n
or \r
. They can be represented in lots of ways, including the <br>
element, or any block element following another (<p></p><p></p>
, for instance).
If you're using a textarea
, you may find \n
or \r
(or \r\n
) for line breaks, so:
var text = $("#theTextArea").val();
var match = /\r|\n/.exec(text);
if (match) {
// Found one, look at `match` for details, in particular `match.index`
}
Live Example | Source
...but that's just textarea
s, not HTML elements in general.
var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
You can simply use this
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With