[英]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: 所以我这样做的方式是:
textarea in question - $("#text")
into a transparent textarea. textarea in question - $("#text")
的textarea in question - $("#text")
到透明文本区域。 Use transparent font. $("#newtext")
and append it to DOM. $("#newtext")
并将其附加到DOM。 this character's 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. this
字符导致换行符。 $("#newtext")
in a loop until $("#newtext")
行,直到 $("#newtext").get(0).scrollHeight() === $("#newtext").height()
this
character, add a \\n
, add this
character to $("#newtext").val()
this
字符前取文字,添加\\n
, this
字符添加到$("#newtext").val()
$("#newtext").val()
to $("#text").val()
. $("#newtext").val()
应用于$("#text").val()
。 $("#newtext")
from DOM. $("#newtext")
。 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.