Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Replace x &nbsp with x spaces at beginning of string

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.

like image 336
Kobi Avatar asked Mar 10 '23 13:03

Kobi


1 Answers

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);
like image 177
James Donnelly Avatar answered Apr 24 '23 22:04

James Donnelly