代码之家  ›  专栏  ›  技术社区  ›  Shard Brian Ellis

删除javascript中的一行文本

  •  32
  • Shard Brian Ellis  · 技术社区  · 16 年前

    在javascript中,如果我有这样的文本块

    Line 1
    Line 2
    Line 3
    

    我需要做些什么,比如删除第一行并将其转换为:

    Line 2
    Line 3
    
    5 回复  |  直到 7 年前
        1
  •  51
  •   Dan Story    16 年前

    最简单的方法是使用split和join函数,它允许您将文本块作为一个行数组来操作,如下所示:

    // 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');
    
        2
  •  35
  •   vsync    8 年前

    这将删除多行字符串变量的第一行-在chrome版本23中对从文件(html5)读取的变量进行测试,其行尾/换行符在记事本+中显示为crlf(回车+换行符):

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

    希望有帮助!

        3
  •  2
  •   LesterDove    16 年前

    简而言之:查找第一行返回(\n)并使用javascript replace 功能删除所有内容(包括它)。

    这是一个雷杰克斯做的(令人惊讶的棘手,至少对我来说…)

    <script type = "text/javascript">
    var temp = new String('Line1\nLine2\nLine3\n');
    temp = temp.replace(/[\w\W]+?\n+?/,"");
    alert (temp);
    </script>
    
        4
  •  0
  •   Eli Grey    16 年前
    var firstLineRemovedString = aString.replace(/.*/, "").substr(1);
    
        5
  •  0
  •   Matt Walterspieler    7 年前

    我更进一步,让您能够从要删除的开始处选择行数:

    我用这个正则表达式 X 是要删除的行数+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));