Is there a better way to add x amount of white space to a string?
str = "blah";
x = 4;
for (var i = 0; i < x; i++){
str = ' ' + str;
}
return str;
Is there a better way to add x amount of white space to a string?
str = "blah";
x = 4;
for (var i = 0; i < x; i++){
str = ' ' + str;
}
return str;
Could do it like this, prevents the loop.
str = str + new Array(x + 1).join(' ')
In ES6 you can do the following:
str = ' '.repeat(x) + str;
At this point in time (late 2014) it's only available in Chrome and Firefox. But in two years it should be widely supported.
See the documentation for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
Alternatively using lodash _.padStart
. Pads string on the left side if it's shorter than length.
const str = 'blah',
len = str.length,
space = 4;
console.log(_.padStart(str, len + space));
// => ' blah'
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Or pure JavaScript:
const str = 'blah',
len = str.length,
space = 4;
console.log(str.padStart(len + space, ' '));
for example you can use repeat for the white space left or right of your string:
var j = 6;
for (i = 0; i < n; i++) {
console.log(" ".repeat(j-1)+"#".repeat(i+1))
j--;
}
You can use padStart
and padEnd
methods.
For eg.:
const str1 = 'Hello';
const str2 = 'World';
const str3 = str1.padEnd(2,' ')+str2.padStart(1,' ');
console.log(str3);
var message = 'stack' + Array(6).fill('\xa0').join('') + 'overflow'
console.log(message);
var message = 'stack' + Array(6).fill('\xa0').join('') + 'overflow'
console.log(message);