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

Solution 1:

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');

Solution 2:

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 ) )

Solution 3:

var firstLineRemovedString = aString.replace(/.*/, "").substr(1);

Solution 4:

In a nutshell: Look for the first line return (\n) and use the JavaScript replace function to remove everything up to it (and including it.)

Here is a RegEx that does it (surprisingly tricky, at least for me...)

<script type = "text/javascript">
var temp = new String('Line1\nLine2\nLine3\n');
temp = temp.replace(/[\w\W]+?\n+?/,"");
alert (temp);
</script>

Solution 5:

You can do this with regex by including the newline character in your search. If the line you want to remove is not at the beginning, you must use the multiline (m) flag.

> var text = "Line 1\nLine 2\nLine 3";
> console.log(text);
Line 1
Line 2
Line 3
> text.replace(/^Line 1\n/m, "");
Line 2
Line 3
> text.replace(/^Line 2\n/m, "");
Line 1
Line 3