且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript:如何使用正则表达式从字符串中删除空行?

更新时间:2023-02-09 13:35:48

您的模式似乎没问题,您只需要包含多行修饰符 m ,所以 ^ $ 匹配行的开头和结尾:

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

如果没有 m ,锚点只匹配字符串开头和结尾。

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

请注意,你错过了在Mac行结尾(仅 \ r )。在这种情况下,这将有所帮助:

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

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

另请注意(在这两种情况下)您不需要匹配可选的 \\ \\ r \\ n 明确地在 \ n 前面,因为这是由 \ * *

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*.

Dex 指出注释,如果它只包含空格(并且后面没有换行符),则无法清除最后一行。解决这个问题的方法是使实际的换行符可选,但在它之前包含一个行尾锚点。在这种情况下,你必须匹配正确结束的行,但是:

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