[removed] how to use a regular expression to remove blank lines from a string?

后端 未结 4 1531
走了就别回头了
走了就别回头了 2020-12-01 03:48

I need to use JavaScript to remove blank lines in a HTML text box. The blank lines can be at anywhere in the textarea element. A blank line can be just a return

相关标签:
4条回答
  • 2020-12-01 03:54

    I believe this will work

    searchText.replace(/(^[ \t]*\n)/gm, "")
    
    0 讨论(0)
  • 2020-12-01 04:02

    This should do the trick i think:

    var el = document.getElementsByName("nameOfTextBox")[0];
    el.value.replace(/(\r\n|\n|\r)/gm, "");
    

    EDIT: Removes three types of line breaks.

    0 讨论(0)
  • 2020-12-01 04:02
    function removeEmptyLine(text) {
      return text.replace(/(\r?\n)\s*\1+/g, '$1');
    }
    

    test:

    console.assert(removeEmptyLine('a\r\nb') === 'a\r\nb');
    console.assert(removeEmptyLine('a\r\n\r\nb') === 'a\r\nb');
    console.assert(removeEmptyLine('a\r\n \r\nb') === 'a\r\nb');
    console.assert(removeEmptyLine('a\r\n \r\n  \r\nb') === 'a\r\nb');
    console.assert(removeEmptyLine('a\r\n \r\n 2\r\n  \r\nb') === 'a\r\n 2\r\nb');
    console.assert(removeEmptyLine('a\nb') === 'a\nb');
    console.assert(removeEmptyLine('a\n\nb') === 'a\nb');
    console.assert(removeEmptyLine('a\n \nb') === 'a\nb');
    console.assert(removeEmptyLine('a\n \n  \nb') === 'a\nb');
    console.assert(removeEmptyLine('a\n \n2 \n  \nb') === 'a\n2 \nb');
    
    0 讨论(0)
  • 2020-12-01 04:15

    Your pattern seems alright, you just need to include the multiline modifier m, so that ^ and $ match line beginnings and endings as well:

    /^\s*\n/gm
    

    Without the m, the anchors only match string-beginnings and endings.

    Note that you miss out on UNIX-style line endings (only \r). This would help in that case:

    /^\s*[\r\n]/gm
    

    Also note that (in both cases) you don't need to match the optional \r in front of the \n explicitly, because that is taken care of by \s*.

    As Dex pointed out in a comment, this will fail to clear the last line if it consists only of spaces (and there is no newline after it). A way to fix that would be to make the actual newline optional but include an end-of-line anchor before it. In this case you do have to match the line ending properly though:

    /^\s*$(?:\r\n?|\n)/gm
    
    0 讨论(0)
提交回复
热议问题