Get last line from text field on keyboard

I have a textarea field and every keystroke, I would like to press the last line in textarea on an array.

I am currently creating an array on each keypress to get the last line in the text box. Is there any way to optimize this? Value, get the last line in the text field without creating an array.

jQuery('#mytextarea').keypress(function() { lines = jQuery('#mytextarea').text().split("\n"); lastLine = lines[lines.length - 1]; 

});

 if(.. some condition ..) { myArray.push(lastLine); 
+4
source share
1 answer

Indeed, there is a way to optimize this. Optimization - this is mainly the use of memory - also improved the use of the CPU.

The optimized version is based on lastIndexOf() . It looks like this:

 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 a DOM element. There is little point in calling jQuery again just to get the text content. Saves a bit in the processor
  • using lastIndexOf allows me to get anything after the last \n

Dogbert provided a guideline for lastIndexOf : http://jsperf.com/splitting-large-strings

+9
source

Source: https://habr.com/ru/post/1483611/


All Articles