Upstart
Upstart

Reputation: 196

Javascript: Insert text at specified line

I am kind of new to javascript, but I was looking to see if it was possible to add a line of text to a file at a specified position? i.e. every file needs to have the same text inserted at line no. 3

Someone suggested "split by line feed, add data, then rejoin", but i have no clue how to do that. Just looking for somewhere to get started or pointed in the right diretion.

Upvotes: 0

Views: 1163

Answers (1)

robbrit
robbrit

Reputation: 17960

Split by line feed:

data = data.split(/\r?\n/);

Add data:

data = data.splice(2, 0, new_data);

Rejoin:

data = data.join("\r\n");

Upvotes: 2

Related Questions