最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Regex to remove white spaces, blank lines and final line break in Javascript - Stack Overflow

programmeradmin0浏览0评论

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)

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

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
2
3

4

Would return the following lines:

["1", "2", "34"]

Can you guys help me out?

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)

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

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
2
3

4

Would return the following lines:

["1", "2", "34"]

Can you guys help me out?

Share Improve this question edited Jul 14, 2015 at 17:08 sigmaxf asked Jul 14, 2015 at 16:53 sigmaxfsigmaxf 8,49215 gold badges70 silver badges132 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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"].

发布评论

评论列表(0)

  1. 暂无评论