JQuery, if a new line, add +1 to the number of lines

I am doing a javascript code editor online, and now I am doing line counting on the left side of the editor. I can’t understand how to do this, when a new line is created, it adds +1 to the line count, so each new line will contain the line number on the left. Does anyone know a good way to do this?

+3
source share
3 answers

You can use string.split()to split each occurrence into an array, and then get the number of arrays.

$('textarea').keyup(function() {
    if ($(this).val().lastIndexOf('\n')!=-1)
        x = $(this).val().split('\n');
    $('div').text(x.length); // This will be the line number
});​

Fiddle

http://jsfiddle.net/WkVb9/

+3
source

Count the number of instances \ n in a string and apply them recursively to the div on the left containing the numbers.

0

, \n, + 1. ...

0

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


All Articles