JavaScript String Nth Line Get

Get Nth Line of a String in JavaScript

A note on how to get an arbitrary line number (Nth line) from multi-line text data in JavaScript. While processing strings line by line is common, getting a specific line (e.g., the ith line) may not be as familiar. This is useful when retrieving a specific line from multi-line strings stored in localStorage.

Shou Arisaka
1 min read
Oct 29, 2025

This is a note on how to get an arbitrary line number (Nth line) from multi-line text data in JavaScript. While itโ€™s common to get and process line by line from a file, there may be fewer situations where you directly specify and get a particular line number.

Method 1: Using split

This method splits the string by line breaks and gets the specific line number.

var str = "hoge\nfuga\nfoo";
var lines = str.split(/\r?\n/);

// Get the 2nd line (index starts from 0, so specify 1)
var secondLine = lines[1]; // "fuga"

Method 2: Managing with JSON Format

This method uses JSON format to manage each line as a key-value pair.

var jsonStr = '{ "1": "hoge", "2": "fuga" }';
var jsonObj = JSON.parse(jsonStr);

// Get the 2nd line
var secondLine = jsonObj["2"]; // "fuga"

You can choose either method depending on the situation and ease of use. Especially when you want to manage line numbers in localStorage or similar, JSON format might be convenient.

Share this article

Shou Arisaka Oct 29, 2025

๐Ÿ”— Copy Links