Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check whether string contains a line break

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.

like image 813
Muhammad Talha Akbar Avatar asked Feb 28 '13 08:02

Muhammad Talha Akbar


People also ask

Can a string have a line break?

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.

How do I find line breaks in a text file?

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

How do you find a new line in a string?

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.


3 Answers

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 textareas, not HTML elements in general.

like image 174
T.J. Crowder Avatar answered Oct 05 '22 19:10

T.J. Crowder


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]);
  }
like image 42
EnterJQ Avatar answered Oct 05 '22 20:10

EnterJQ


You can simply use this

var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;

like image 42
Ajinkya Bodade Avatar answered Oct 05 '22 18:10

Ajinkya Bodade