How to – Display Multiple Spaces Using innerHTML

Have you ever tried to display multiple spaces in a page element using innerHTML property with javascript? If so then you probably encountered this problem of collapsing multiple spaces.

Apparently this is how HTML works. It collapses multiple spaces into one space until you specifically tell him otherwise.

For example let's say you have a string like “my   string    with    multiple     spaces”. If you try to set this string to the innerHTML property of a div element like below;

myDiv.innerHTML = “my       string        with      multiple        spaces”;

Then myDiv will display your string as “my string with multiple spaces” collapsing multiple spaces.

In order to avoid this problem and display each and every space that you have in your string you have to perform a replacement on your string. You have to replace each space with their unicode representation in javascript which is “u00A0”.

mystring = “my       string        with      multiple        spaces”;
mystring = mystring.replace(/ /g, “u00A0”);

After doing the above replacement you are good to go…

myDiv.innerHTML=mystring;

And you have all your spaces in place and visible.

Hope this helps someone.

Good luck,
Serdar.

2 thoughts on “How to – Display Multiple Spaces Using innerHTML

  1. You can also just replace all the spaces with   which is the equivalent of u00A0, but probably won’t be as likely to break if the page has a weird character set .

Leave a Reply

Your email address will not be published. Required fields are marked *