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

I want to remove the place at the beginning of each line.

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

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

How to add ^\s condition to replace() ?

+6
source share
3 answers

To remove all leading spaces:

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

The regular expression is pretty simple - one or more spaces at the beginning. More interesting bits are the flags - /g (global) to replace all matches, not just the first ones, and /m (multi-line) so that the caret matches the beginning of each line, and not just the beginning of the line.

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

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

it supports several spaces of different types, including tabs.

+4
source

If you only need to remove one space, then this regular expression is all you need:

 ^\s 

So, in JavaScript:

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

Source: https://habr.com/ru/post/886763/


All Articles