Javascript - Adding White Space to Left of String

How to add a space at the end of a string in Javascript

By default, the browser will "collapse" all spaces into a single space.

One solution is to use the <pre> element for the output instead. Like this:

<pre type="text" id="outputNumber1"></pre>

<pre> shows pre-formatted text. So the output is displayed with all spaces and newlines preserved.

If you don't want to change the element type, you can add the CSS declaration white-space:pre to the element to achieve the same result as above. Like this:

<output type="text" id="outputNumber1" style="white-space:pre;"></output>

or you can set it separately in your <style> block like this:

<style>
body{background-color: green;}
#outputNumber1{white-space:pre;}
</style>

Is there a way to add white space in a string based on the array length it is in

You could take a function and hand over the left and right part of the string and get a combined string with spaces.

function pad(left, right, size) {    left = left.toString();    right = right.toString();    return left + ''.padStart(size - left.length - right.length) + right;}

let formattedData = [['Cafe Latte', 2 + ' x ' + 4.75], ['Americano', 4 + ' x ' + 3.75]], result = formattedData.map(a => pad(...a, 30));
console.log(result);

Adding white space to the right of a string

For instance, you should try :

str = str + ' ';

More concise :

str += ' ';

How to add spaces around a certain character in a javascript string?

You aren't setting the HTML, and that's why the nbsp fails:

var str = 'param1 | param2 |      param3 | param4';document.getElementById('a').innerHTML = str;
<div id='a'></div>

Adding equal amount of whitespace to both ends of string

If numspace is an integer, then you can use that value as the upper boundary in a for loop like so:

function space(str, numspace){    var emptySpace = "";    for (i = 0; i < numspace; i++){        emptySpace += " ";    }    var output = emptySpace + str + emptySpace;    return output;}
console.log("'" + space('example1', 5) + "'");console.log("'" + space('example2', 3) + "'");console.log("'" + space('example3', 1) + "'");

Adding whitespace in a Javascript document.write

If you want to add whitespace to the DOM, try using a nonbreaking space

' '

instead of

' '

These nonbreaking spaces can be chained.

  

would force two spaces to be displayed on the page.



Related Topics



Leave a reply



Submit