Javascript: Replace x & nbsp with spaces x at the beginning of the line

Given a line with an unknown number of spaces at the beginning.

I would like to replace each of the spaces with  .

ONLY spaces at the beginning of a line should be replaced.

It:

'   This is a string with 3 spaces at the beginning';

Must translate to:

'   This is a string with 3 spaces at the beginning'

And this:

'     This is a string with 5 spaces at the beginning';

Must translate to:

'     This is a string with 5 spaces at the beginning'

I am looking for a solution that does not require a loop through the spaces of the string.

+4
source share
2 answers

This should do the trick:

str.replace(/^ */, function(match) {
  return Array(match.length + 1).join(" ")
});

This matches zero or more spaces at the beginning of the line, then determines the number of spaces (using match.length), then repeats the " "given number of times (using this solution ).


var str = '     This is a string with 5 spaces at the beginning';

var result = str.replace(/^ */, function(match) {
  return Array(match.length + 1).join(" ")
});

console.log(result);
Run codeHide result
+7

.

.

/\s/g  

^/\s+/ ( )  .

var str="     This is a string with 5 spaces at the beginning";
str2=str.split(/[^\s]/)[0];
str2=str2.replace(/\s/g,' ');
str=str.replace(/^\s+/,str2);
console.log(str);
Hide result
0

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


All Articles