1

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?

3 Answers 3

2

Use the multiline mode:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks guys! Both pretty quick! I'll accept yours since your rep is lower than @Barmar's, but thanks to both of you.
2

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.