4

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

I would like to replace each of the spaces with a  .

ONLY the spaces at the beginning of the string should be replaced.

This:

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

Should translate to:

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

And this:

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

Should translate to:

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

I'm looking for a solution that doesn't required looping through the spaces of the string.

Kobi
  • 53
  • 5

2 Answers2

7

This should do the trick:

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

This matches on zero or more spaces at the start of a string, then determines how many spaces there are (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);
Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Great answer. But note that joining the array returns one item less than the `match.length` count. So maybe more accurate solution would be: `Array(match.length + 1).join(" ")` – Kobi Mar 22 '17 at 11:24
  • 1
    @Cobi yeah I noticed my error myself a couple of minutes ago but wasn't sure if you'd already seen it so didn't mention anything. The answer is already fixed. :) – James Donnelly Mar 22 '17 at 11:24
0

You want to replace only the first spaces.

Split it with regex and take the first value on array.

replace /\s/g with   in the first part

Again, from the original word, replace ^/\s+/ (that is the starting space sequence) with the   sequence word.

As I did in the code below

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);
Sagar V
  • 12,158
  • 7
  • 41
  • 68
  • Absolutely unnecessary `split` step. Looks like you don't know how to use `replace` properly (using callback function). – dfsq Mar 22 '17 at 11:26