Delete a line of text in javascript

前端 未结 7 1558
甜味超标
甜味超标 2020-12-13 17:44

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 in

相关标签:
7条回答
  • 2020-12-13 17:52

    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');
    
    0 讨论(0)
  • 2020-12-13 17:53

    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>
    
    0 讨论(0)
  • 2020-12-13 17:58

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

    0 讨论(0)
  • 2020-12-13 18:03
    var firstLineRemovedString = aString.replace(/.*/, "").substr(1);
    
    0 讨论(0)
  • 2020-12-13 18:06

    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
    
    0 讨论(0)
  • 2020-12-13 18:07

    Try this

    Taking advantage of JavaScript classess

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

    I hope this helps someone

    0 讨论(0)
提交回复
热议问题