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

后端 未结 4 1542
走了就别回头了
走了就别回头了 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 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');
    

提交回复
热议问题