AlbertEngelB
AlbertEngelB

Reputation: 16456

Regex To Remove Spaces Between Newlines and Content

So I want to remove any spaces that lay between a new line and content.

 this

  is
    some

  content
son

          best
  believe

Should turn into:

this

is
some

content
son

best
believe

I've tried doing something like this, but it doesn't seem to do the trick:

string.replace(/^\s*/g, '');

Any ideas?

Upvotes: 1

Views: 277

Answers (3)

hwnd
hwnd

Reputation: 70750

You could simply do the following.

string.replace(/^ +/gm, '');

Regular expression:

^     the beginning of the string
 +    ' ' (1 or more times (matching the most amount possible))

The g modifier means global, all matches. The m modifier means multi-line. Causes ^ and $ to match the begin/end of each line.

See example

Upvotes: 2

Barmar
Barmar

Reputation: 782745

You need the m modifier so that ^ will match newlines rather than the beginning of the string:

string.replace(/^\s*/gm, '');

Upvotes: 1

Jerry
Jerry

Reputation: 71598

Use the multiline mode:

string = string.replace(/^\s*/gm, '');

This makes ^ match the beginning of each line instead of the whole string.

Upvotes: 2

Related Questions