Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a line of text in javascript

In javascript, If i have a text block like so

Line 1 Line 2 Line 3 

What would i need to do to lets say delete the first line and turn it into:

Line 2 Line 3 
like image 628
Shard Avatar asked Mar 27 '10 03:03

Shard


People also ask

Does JavaScript trim remove newline?

trim method removes any line breaks from the start and end of a string. It handles all line terminator characters (LF, CR, etc). The method also removes any leading or trailing spaces or tabs. The trim() method doesn't change the original string, it returns a new string.

How do you remove the first line of a string in Java?

Assuming there's a new line at the end of the string that you would like to remove, you can do this: s = s. substring(s. indexOf('\n')+1);


2 Answers

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 lines var lines = textblock.split('\n'); // remove one line, starting at the first position lines.splice(0,1); // join the array back into a single string var newtext = lines.join('\n'); 
like image 114
Dan Story Avatar answered Sep 30 '22 08:09

Dan Story


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 = `first second third`;  // 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 ) )
like image 23
Kozuch Avatar answered Sep 30 '22 08:09

Kozuch