Delete a line of text in javascript

JavascriptText

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - 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 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 - Javascript

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

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

Solution 4 - Javascript

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

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

Solution 6 - Javascript

Try taking advantage of JavaScript classes.

object() - split the string defined in the constructor into array of lines and method real_array loops through the array and ensure there is no empty member in the array

constructor(string){
    this.string = string;
    this.value = string;
}


object(){ 
    return this.real_array(this.value.split('\n')); 
}
// returns ['Line 1','Line 2','Line 3']

remove(string_to_be_removed) - collects the string you intend to remove by deleting the member of the array equal to string_to_be_removed

remove(string_to_be_removed){
    var _object = this.object();
    _object.forEach((value,index) => {
    
        if (value.trim()===string_to_be_removed){
             delete _object[index];
        }
    });
    this.value = this.real_array(_object).join('\n');
    return this;
}

/*
new line(`Line 1
Line 2
Line 3`).remove('Line 1').value //returns 

Line 2
Line 3

*/

Full code:

// Your code here!
class line{
    constructor(string){
        this.string = string;
        this.value = string;
    }
    
    object(){ 
        return this.real_array(this.value.split('\n')); 
    }


    remove(string_to_be_removed){
        var _object = this.object();
        _object.forEach((value,index) => {
            if (value.trim()===string_to_be_removed){
                delete _object[index];
            }
        });
        this.value = this.real_array(_object).join('\n');
        return this;
    }


    removeAll(string_to_be_removed){
        var _object = this.object();
        _object.forEach((value,index) => {
            if (value.trim().indexOf(string_to_be_removed)!=-1){
                delete _object[index];
            }
        });
        this.value = this.real_array(_object).join('\n');
        return this;
    }

    fetch(line_number){
        var _object = this.object();
        for (let i=0;i<_object.length;i++){
            if (i+1===line_number){
                return _object[i];
            }
        }
        return null;
    }


    edit(content,line_number){
         var _object = this.object();
        _object[line_number-1] = content;
         this.value = this.real_array(_object).join('\n');
         return this;
     }

    
    real_array(array){
    	var output = [];
    	array.forEach(element=>{
    		if (element.trim().length>0){
    			output.push(element);
    		}
    	});
    	return output;
    }
}
var string = `1
2
3
Remove this
5
3
3
Remove this all
4
6
Remove this all and this
`

var line_string = new line(string)
console.log("Fetch with line number")
console.log(line_string.fetch(3))
console.log("-------------------")

console.log("Remove line by the string content on the line")
console.log(line_string.remove('Remove this').value);
console.log("------------")


console.log("Remove all occurrence of line by the string content on the lines")
console.log(line_string.removeAll('Remove this').value);
console.log("-------------------")

console.log("Edit line") console.log(line_string.edit("I edited it",2).edit("I also edit this",5).value);

Solution 7 - Javascript

I went a bit further to let you be able to select the number of lines from the beginning you want to delete:

I use this regular expression where X is the number of line you want to delete +1 (?:.*?\n){X}(?:.*?\n)

const lines = Line1 Line2 Line3 Line4; const deleteLines = (string, n = 1)=>{ return string.replace(new RegExp((?:.*?\n){${n-1}}(?:.*?\n)), ''); }; console.log(deleteLines(lines, 2));

Solution 8 - Javascript

Flow

Below solution use flow pattern which based on js-arrays and is not inplace and allows to continue string processing by 'dot' (snippet) - (the N is delete line index starting from zero)

text.split`\n`.filter((l,i)=> i != N).join`\n`

let text=`Line 1
Line 2
Line 3`;

let noFirst = text.split`\n`.filter((l,i)=> i!=0).join`\n`.toUpperCase();

console.log(noFirst);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShardView Question on Stackoverflow
Solution 1 - JavascriptDan StoryView Answer on Stackoverflow
Solution 2 - JavascriptKozuchView Answer on Stackoverflow
Solution 3 - JavascriptEli GreyView Answer on Stackoverflow
Solution 4 - JavascriptLesterDoveView Answer on Stackoverflow
Solution 5 - JavascriptEllis PercivalView Answer on Stackoverflow
Solution 6 - JavascriptAkintomiwa OpemipoView Answer on Stackoverflow
Solution 7 - JavascriptMatt WalterspielerView Answer on Stackoverflow
Solution 8 - JavascriptKamil KiełczewskiView Answer on Stackoverflow