简体   繁体   English

正则表达式删除Javascript中的空格,空行和最后一行换行符

[英]Regex to remove white spaces, blank lines and final line break in Javascript

Ok guys, I'm having a hard time with regex.. 好的,我正在用正则表达式来度过难关..

Here's what I need... get a text file, remove all blank lines and white spaces in the beginning and end of these lines, the blank lines to be removed also include a possible empty line at the end of the file (a \\n in the end of the whole text) 这就是我需要的...获取文本文件,删除所有空白行和这些行的开头和结尾处的空格,要删除的空白行还包括文件末尾的空行(a \\ n在全文的最后)

So my script was: 所以我的脚本是:

quotes.replace(/^\s*[\r\n]/gm, "");

This replaces fairly well, but leaves one white space at the end of each line and doesn't remove the final line break. 这取代相当不错,但在每行的末尾留下一个空格,并且不会删除最后的换行符。

So I thought using something like this: 所以我想用这样的东西:

quotes.replace(/^\s*[\r\n]/gm, "").replace(/^\n$/, "");

The second "replace" would remove a final \\n from the whole string if present.. but it doesn't work.. 第二个“替换”将从整个字符串中删除最后的\\ n如果存在..但它不起作用..

So I tried this: 所以我尝试了这个:

quotes.replace(/^\s*|\s*$|\n\n+/gm, "")

Which removes line breaks but joins some lines when there is a line break in the middle: 这会删除换行符,但在中间有换行符时连接一些换行符:

so that 以便
1 1
2 2
3 3

4 4

Would return the following lines: 将返回以下行:

["1", "2", "34"] [“1”,“2”,“34”]

Can you guys help me out? 你能帮助我吗?

Since it sounds like you have to do this all in a single regex, try this: 既然听起来你必须在一个正则表达式中完成所有这一切,试试这个:

quotes.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm,"")

What we are doing is creating a group that captures nothing, but prevents a newline by itself from getting consumed. 我们正在做的是创建一个不会捕获任何内容的组,但是防止换行本身被消耗掉。

Split, replace, filter: 拆分,更换,过滤:

quotes.split('\n')
    .map(function(s) { return s.replace(/^\s*|\s*$/g, ""); })
    .filter(function(x) { return x; });

With input value " hello \\n\\nfoo \\n bar\\nworld \\n" , the output is ["hello", "foo", "bar", "world"] . 输入值为" hello \\n\\nfoo \\n bar\\nworld \\n" ,输出为["hello", "foo", "bar", "world"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM