How to count lines in Javascript
Tags: javascript, node, webdev, programming
Published: 2024-03-11 16:01:38

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](https://blankhtml.com/text-tools/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](https://dev.to/websilvercraft/how-to-count-lines-of-code-3dnp)

## 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:

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

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

console.log(countLinesInString(myString)); // This will output: 3
```

## Count Lines in a Textarea Element

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

```javascript
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
```

## 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:

```javascript
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);
});
```

## 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:

```javascript
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');
```

## Counting source code lines

I've created a separate post, on [how to count source code lines](https://dev.to/websilvercraft/how-to-count-lines-of-code-3dnp), using bash or cloc command line tool, available on win/mac/linux.

In the tool which is published on [blank html](https://blankhtml.com/), 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.