35

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.

Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62

3 Answers3

57

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
15
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]);
  }
EnterJQ
  • 1,014
  • 8
  • 18
5

You can simply use this

var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
linktoahref
  • 7,812
  • 3
  • 29
  • 51
Ajinkya Bodade
  • 491
  • 1
  • 5
  • 11