DEV Community

websilvercraft
websilvercraft

Posted on

How to count lines in Javascript

It happens quite often that I need to count the lines in a text in javascript, so I created an online tool to count lines in Javascript. I sharing here the snippets to count lines in different contexts:

  • Count Lines in a String
  • Count Lines in a Textarea Element
  • Counting Lines in a File using the Browser
  • Counting Lines in a File (Node.js)
  • Counting source code lines

Count Lines in a String

To find out how many lines a given string comprises, one can utilize the method of splitting the string using the newline character (\n) and then determining the length of the resulting array. Here is how it can be done:

function countLinesInString(str) {
    return str.split('\n').length;
}

const myString = `Line 1
Line 2
Line 3`;

console.log(countLinesInString(myString)); // This will output: 3
Enter fullscreen mode Exit fullscreen mode

Count Lines in a Textarea Element

When you need to count the number of lines within a element, the process is quite straightforward. Since the content of a is a string with lines separated by newline characters, you can count the lines in a similar manner to a regular string:

function countLinesInTextarea(textareaElement) {
    return textareaElement.value.split('\n').length;
}

const textarea = document.getElementById('myTextarea');
console.log(countLinesInTextarea(textarea)); // This will output the total number of lines
Enter fullscreen mode Exit fullscreen mode

Counting Lines in a File using the Browser

For scenarios where you're working with file inputs in a browser context, you can leverage the FileReader API to read the contents of a user-selected file. After reading the file, you can count the number of lines by splitting the text at each newline character:

function countLinesInFile(file) {
    const reader = new FileReader();

    reader.onload = function(event) {
        const text = event.target.result;
        const lineCount = text.split('\n').length;
        console.log(lineCount); // This will output the total number of lines
    };

    reader.readAsText(file);
}

// Example of usage
// Assuming there's a file input element:
document.getElementById('fileInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    countLinesInFile(file);
});
Enter fullscreen mode Exit fullscreen mode

Counting Lines in a File (Node.js)

In a Node.js environment, when the goal is to count the lines in a file, you can do so by reading the file with the fs module. Once the file's contents are read, count the lines by splitting the text by newline characters:

const fs = require('fs');

function countLinesInFile(filePath) {
    fs.readFile(filePath, 'utf8', function(err, data) {
        if (err) {
            console.error(err);
            return;
        }
        const lineCount = data.split('\n').length;
        console.log(lineCount); // This will output the number of lines
    });
}

countLinesInFile('path/to/your/file.txt');
Enter fullscreen mode Exit fullscreen mode

Counting source code lines

I've created a separate post, on how to count source code lines, using bash or cloc command line tool, available on win/mac/linux.

In the tool which is published on blank html, I used a text area where the user can paste a text and when it's updated the line count is displayed along with word count, character count and keyword frequency.

Top comments (0)