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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15131072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:26:12  来源:igfitidea点击:

check whether string contains a line break

javascriptjquery

提问by Muhammad Talha Akbar

So, I have to get HTML of textarea and check whether it contains line break. How can i see whether it contain \nbecause the string return using val()does not contain \nand 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 \nto textarea as value, it breaks and move to next line.

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

回答by T.J. Crowder

Line breaks in HTML aren't represented by \nor \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。它们可以用多种方式表示,包括<br>元素,或任何跟在另一个元素之后的块元素(<p></p><p></p>例如)。

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

如果您使用的是textarea,您可能会发现\n\r(或\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 元素。

回答by EnterJQ

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