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;
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') .
Use the padEnd() and padStart() methods to add spaces to the end or beginning of a string, e.g. str. padEnd(6, ' '); . The methods take the maximum length of the new string and the fill string and return the padded string. Copied!
So, how can you add white to the DOM in JavaScript? The best way to add white space to use a unicode literal for a non-breaking space. Instead of specifying non-breaking space with we can instead use \xC2\xA0 . This ensures that the non-breaking space is evaluated correctly when the markup is being rendered.
The break tag is meant for single line breaks, and not more than one in a row. If you want to add extra whitespace between pieces of text, use CSS padding and margins instead for cleaner code. Or, you can use an HTML <p> tag, as we'll see next.
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--;
}
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