admin管理员组文章数量:1287626
I have a textarea field and on every keypress, I would like to push the last line in the textarea to an array.
Currently, I am constructing the array on every keypress to get the last line in the textarea. Is there a way to optimize this? Meaning, get last line in the textarea without having to construct an array.
jQuery('#mytextarea').keypress(function() {
lines = jQuery('#mytextarea').text().split("\n");
lastLine = lines[lines.length - 1];
});
if(.. some condition ..) {
myArray.push(lastLine);
I have a textarea field and on every keypress, I would like to push the last line in the textarea to an array.
Currently, I am constructing the array on every keypress to get the last line in the textarea. Is there a way to optimize this? Meaning, get last line in the textarea without having to construct an array.
jQuery('#mytextarea').keypress(function() {
lines = jQuery('#mytextarea').text().split("\n");
lastLine = lines[lines.length - 1];
});
if(.. some condition ..) {
myArray.push(lastLine);
Share
Improve this question
asked May 30, 2013 at 15:17
Srikanth ADSrikanth AD
1,8542 gold badges14 silver badges19 bronze badges
11
-
why are u using
jQuery
instead of$
? just curious. – PlantTheIdea Commented May 30, 2013 at 15:19 - Just a personal preference. – Srikanth AD Commented May 30, 2013 at 15:20
- 2 Why would you need to optimize this? This will take a nano second to execute and its not executed on your server. – Deepsy Commented May 30, 2013 at 15:20
- 1 You could use the blur event and then read the last line. Not sure why you want to do it on every single key press. – Dave Commented May 30, 2013 at 15:21
- 1 As the content of the textarea grows, on every keypress - an array is being constructed just to get the last line. I wish I did not have to construct the array on every keypress. Moreover, I am not manipulating the array in any way so, I am looking for ways to optimize this. – Srikanth AD Commented May 30, 2013 at 15:22
1 Answer
Reset to default 11Indeed, there is a way to optimize this. The optimization is mostly memory usage - the actual CPU usage is also improved.
The optimized version relies on lastIndexOf()
. It is as follows:
jQuery("#mytextarea").keypress(function() {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n")+1);
});
You will notice a couple of micro-optimizations:
this
already is the DOM element. There is little point in re-invoking jQuery just to get the text content. Saves a bit on processor- using
lastIndexOf
allows me to get anything after the last\n
Dogbert provided a benchmark for the lastIndexOf
: http://jsperf./splitting-large-strings
本文标签: javascriptGet last line from a textarea on keypressStack Overflow
版权声明:本文标题:javascript - Get last line from a textarea on keypress - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741306460a2371396.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论