Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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()?

like image 713
kiran Avatar asked Apr 27 '11 05:04

kiran


1 Answers

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

like image 61
Kobi Avatar answered Sep 20 '22 13:09

Kobi