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);
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 processorlastIndexOf
allows me to get anything after the last \n
Dogbert provided a benchmark for the lastIndexOf
: http://jsperf.com/splitting-large-strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With