JavaScript:如何使用正则表达式从字符串中删除空行? [英] JavaScript: how to use a regular expression to remove blank lines from a string?
问题描述
我需要使用JavaScript删除HTML文本框中的空行。空行可以位于 textarea
元素中的任何位置。空行可以只是一个返回或空格加返回。
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 or white spaces plus return.
我期待一个正则表达式解决方案。以下是我试过的一些,但它们无法正常工作,无法找出原因:
I am expecting a regular expression solution to this. Here are some I tried, but they are not working and cannot figure out why:
/^\s*\r?\n/g
/^\s*\r?\n$/g
编辑1
似乎aaronman和m建议的解决方案(我稍微修改了一下) .buettner的工作原理:
It appears that the solution (I modified it a little) suggested by aaronman and m.buettner works:
string.replace(/^\s*\n/gm, "")
有人能说出为什么我的第一个正则表达式不起作用吗?
Can someone tell why my first regular expression is not working?
编辑2
阅读完所有有用的答案后,我想出了这个:
After reading all useful answers, I came up with this:
/^[\s\t]*(\r\n|\n|\r)/gm
这是否适用于所有情况?
Is this going to be one that cover all situations?
编辑3
这是最简洁的一个,涵盖所有空格(空格,标签)和平台(Linux,Windows,Mac)。
This is the most concise one covering all spaces (white spaces, tabs) and platforms (Linux, Windows, Mac).
/^\s*[\r\n]/gm
非常感谢m.buettner!
Many thanks to m.buettner!
推荐答案
您的模式似乎没问题,您只需要包含多行修饰符 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
这篇关于JavaScript:如何使用正则表达式从字符串中删除空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!