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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With