检查字符串是否包含换行符

时间:2021-02-18 07:22:27

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 ?

所以,我必须得到textarea的HTML并检查它是否包含换行符。我怎么能看到它是否包含\ n因为使用val()返回的字符串不包含\ n而且我无法检测到它。我尝试使用.split(“\ n”),但它给出了相同的结果。如何做呢 ?

One minute, IDK why when i add \n to textarea as value, it breaks and move to next line.

一分钟,IDK为什么当我将\ n添加到textarea作为值时,它会中断并移动到下一行。

2 个解决方案

#1


30  

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

HTML中的换行符不用\ n或\ r表示。它们可以用很多方式表示,包括
元素,或者跟随另一个元素的任何块元素(例如

)。

If you're using a textarea, you may find \n or \r (or \r\n) for line breaks, so:

如果你正在使用textarea,你可能会发现\ n或\ r \ n(或\ r \ n)换行符,所以:

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.

...但这只是textareas,而不是一般的HTML元素。

#2


6  

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]);
  }

#1


30  

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

HTML中的换行符不用\ n或\ r表示。它们可以用很多方式表示,包括
元素,或者跟随另一个元素的任何块元素(例如

)。

If you're using a textarea, you may find \n or \r (or \r\n) for line breaks, so:

如果你正在使用textarea,你可能会发现\ n或\ r \ n(或\ r \ n)换行符,所以:

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.

...但这只是textareas,而不是一般的HTML元素。

#2


6  

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]);
  }