简体   繁体   English

Textarea - 获取每一行,找到换行符

[英]Textarea - get each line, find line breaks

I want to get each line in a textarea. 我想在textarea中获得每一行。 The textarea is small and wraps words according to width constraints. textarea很小,根据宽度限制包装单词。 So I tried: 所以我尝试过:

// Sample text: I want to find(line wrapped) all lines here

$("#textarea1").val().split(/(\r\n|\n|\r)/gm).length
// 1, not the right length, should be 2

$("#textarea1").val().split(/\r?\n/g).length
// 1

$("#textarea1").val().split("\n").length
// 1

$("#textarea1").val().split("\r").length
// 1

I also tried wrap="hard" and white-space: pre-wrap individually and together. 我也试过wrap="hard"white-space: pre-wrap单独和一起white-space: pre-wrap

Nothing seems to find line-breaks !! 似乎没有找到换行符 !! Need help, thanks. 需要帮助,谢谢。

I think it's just like you said: the textarea wraps words according to width constraints — which means are no line breaks for you to find. 我认为就像你说的那样:textarea根据宽度限制包装单词 - 这意味着你找不到换行符。 The line breaks you're looking for are characters, and those characters have not been inserted into your text. 您要查找的换行符是字符,并且这些字符尚未插入到您的文本中。

So the way I did it was: 所以我这样做的方式是:

  • Clone the textarea in question - $("#text") into a transparent textarea. 克隆有textarea in question - $("#text")textarea in question - $("#text")到透明文本区域。 Use transparent font. 使用透明字体。
  • Change id value of clone to, say, $("#newtext") and append it to DOM. 将clone的id值更改为,例如$("#newtext")并将其附加到DOM。
  • On every keyup, we take the value of $("#text") before this character's keyup . 在每个keyup上,我们在this character's keyup之前取值$(“#text”)。 Put that value into $("#newtext") and check if $("#newtext").get(0).scrollHeight() > $("#newtext").height() . 将该值放入$("#newtext")并检查$("#newtext").get(0).scrollHeight() > $("#newtext").height() If true => this character caused a line break. 如果为true => this字符导致换行符。
  • Increase rows of $("#newtext") in a loop until 在循环中增加$("#newtext")行,直到
    $("#newtext").get(0).scrollHeight() === $("#newtext").height()
  • Take text before this character, add a \\n , add this character to $("#newtext").val() this字符前取文字,添加\\nthis字符添加到$("#newtext").val()
  • Apply $("#newtext").val() to $("#text").val() . $("#newtext").val()应用于$("#text").val()
  • Remove $("#newtext") from DOM. 从DOM中删除$("#newtext")
  • Repeat all of above steps on every keyup event 在每个keyup事件上重复上述所有步骤

Above answer works on similar lines as - stackoverflow.com/questions/3738490/finding-line-wraps – evolutionxbox yesterday 以上答案适用于类似的行 - stackoverflow.com/questions/3738490/finding-line-wraps - evolutionxbox昨天

So, basically we convert line breaks into newlines which can be found by using $("#text").val().split("\\n") . 因此,基本上我们将换行符转换为换行符,可以使用$("#text").val().split("\\n")

(Note - If we don't append transparent textarea to the DOM, its scrollHeight() will be undefined ) (注意 - 如果我们不将透明文本区域附加到DOM,则其scrollHeight()将是undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM