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

前端 未结 2 1315
花落未央
花落未央 2021-01-14 06:36

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

相关标签:
2条回答
  • 2021-01-14 07:01

    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.

    0 讨论(0)
  • 2021-01-14 07:07

    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 讨论(0)
提交回复
热议问题