Delete a line of text in javascript Delete a line of text in javascript javascript javascript

Delete a line of text in javascript


The cleanest way of doing this is to use the split and join functions, which will let you manipulate the text block as an array of lines, like so:

// break the textblock into an array of linesvar lines = textblock.split('\n');// remove one line, starting at the first positionlines.splice(0,1);// join the array back into a single stringvar newtext = lines.join('\n');


This removes the first line from a multi-line string variable - tested in Chrome version 23 on a variable which was read from file (HTML5) with line endings/breaks that showed as CRLF (carriage return + line feed) in Notepad++:

var lines = `firstsecondthird`;// cut the first line:console.log( lines.substring(lines.indexOf("\n") + 1) );// cut the last line:console.log( lines.substring(lines.lastIndexOf("\n") + 1, -1 ) )