kiran
kiran

Reputation: 133

Regular expression to remove space in the beginning of each line?

I want to remove space in the beggining of each line.

I have data in each line with a set of spaces in the beginning so data appears in the middle, I want to remove spaces in the beginning of each line.

tmp = tmp.replace(/(<([^>]+)>)/g,"")

How can I add the ^\s condition into that replace()?

Upvotes: 12

Views: 30351

Answers (3)

Gabriel
Gabriel

Reputation: 18780

var text = "          this is a string         \n"+
           "    \t    with a much of new lines     \n";
text.replace(/^\s*/gm, '');

this supports multiple spaces of different types including tabs.

Upvotes: 12

Kobi
Kobi

Reputation: 138017

To remove all leading spaces:

str = str.replace(/^ +/gm, '');

The regex is quite simple - one or more spaces at the start. The more interesting bits are the flags - /g (global) to replace all matches and not just the first, and /m (multiline) so that the caret matches the beginning of each line, and not just the beginning of the string.

Working example: http://jsbin.com/oyeci4

Upvotes: 31

BraedenP
BraedenP

Reputation: 7215

If all you need is to remove one space, then this regex is all you need:

^\s

So in JavaScript:

yourString.replace(/(?<=\n) /gm,"");

Upvotes: 1

Related Questions