Santanu Karar
Santanu Karar

Reputation: 1076

AS3 keep blank lines but remove leading spaces before word after line breaks

Actual:

 A new line begins

     Another line begins
       Here's another

Expected:

A new line begins

Another line begins
Here's another

So far I have tried this which removes all the leading spaces before word after line breaks:

var regex:RegExp = /(\r?\n|\r)+(\s+|\s+$)/g;
var newText:String = abcd.replace(regex, "\n");
Alert.show(StringUtil.trim(newText));

But I'm having difficulty to set a condition to leave blank lines as they are.

Upvotes: 2

Views: 232

Answers (1)

Kobi
Kobi

Reputation: 138017

A simple option is to match and remove only the spaces at the start of lines, and never newlines:

var regex:RegExp = /^[ \t]+/gm;
var newText:String = abcd.replace(regex, "");
  • Use the /m (multiline) flag, so ^ matches at the beginning of every line.
  • Match only spaces and tabs, not line breaks.
  • Simply remove them.
  • This will also remove spaces from space-only lines. If that's a problem you can use ^[ \t]+(?=\S).

Working example: https://regex101.com/r/gdMZLZ/2

Upvotes: 2

Related Questions