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
 |  Show 6 more ments

1 Answer 1

Reset to default 11

Indeed, 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