How to Type Spaces In HTML Input And Display In the Browser

When we type a space in an input and use it in JavaScript. The space will be recorded as text just like regular texts.

Type In Multiple Spaces

When we type some text with many spaces and displays the text in the browser, muiltple spaces will be parsed into one space, if they are connected.
Type some text with spaces here:
<input oninput="show_1.innerHTML = this.value" /><br />
<div id="show_1"></div>

What does JavaScript Do to the Spaces?

JavaScript does nothing to the spaces. It preservs all the spaces we type. The following code converts spaces into the letter "a". Space is represnted by \x20 in JavaScript.
Type some text with spaces here:
<input oninput="show_2.innerHTML = this.value.replace(/\x20/g,'a');" /><br />
<div id="show_2"></div>

Why doesn't the Spaces Show in the Browser?

Because the connected spaces are parsed into one space in HTML.
<div id = "show_3"></div>
<div id = "show_4"></div>
<script>
var text = "a   a";
document.getElementById("show_3").innerHTML = text;
// a a
document.getElementById("show_4").innerText = text;
</script>
While the show_3 and show_4 both have innerHTML of "a a" and innerText of "a a". This means innerText is the result of innerHTML after being parsed via HTML.

How to Type Spaces In HTML Input And Display In the Browser

Replace all spaces with "&nbsp;"
Type some text with spaces here:
<input oninput="show_5.innerHTML = this.value.replace(/\x20/g,'&nbsp;');" /><br />
<div id="show_5"></div>
By the way, &nbsp; is the HTML space while \x20 is the JavaScript space. If you replace &nbsp;  with \x20, spaces will sitll not show up.
Type some text with spaces here:
<input oninput="show_5.innerHTML = this.value.replace(/\x20/g,'\x20');" /><br />
<div id="show_5"></div>
When /x20 in a JavaScript string is the exactly the same with a space.
console.log("a  a" == "a a");
//false

console.log("a  a" == "a&nbsp;&nbsp;a");
//false

console.log("a  a" == "a\x20\x20a");
//true
</script>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title