Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last line from a textarea on keypress

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);
like image 334
Srikanth AD Avatar asked Dec 27 '22 03:12

Srikanth AD


1 Answers

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.com/splitting-large-strings

like image 56
Sébastien Renauld Avatar answered Jan 07 '23 03:01

Sébastien Renauld