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.