Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - adding white space to left of string

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;
like image 541
K3NN3TH Avatar asked Sep 14 '14 00:09

K3NN3TH


People also ask

How do you add a white space to a string?

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(' ') .

How do you put a space in a string in JavaScript?

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!

How do I create a white space in JavaScript?

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 &nbsp; we can instead use \xC2\xA0 . This ensures that the non-breaking space is evaluated correctly when the markup is being rendered.

How do you leave a space in JavaScript?

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.


4 Answers

Could do it like this, prevents the loop.

str = str + new Array(x + 1).join(' ')

like image 156
Declan Cook Avatar answered Oct 20 '22 00:10

Declan Cook


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

like image 21
slebetman Avatar answered Oct 20 '22 00:10

slebetman


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, ' '));
like image 24
Penny Liu Avatar answered Oct 19 '22 23:10

Penny Liu


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--;
}
like image 39
Ezequiel García Avatar answered Oct 20 '22 01:10

Ezequiel García