Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a non-breaking whitespace in JavaScript without using innerHTML?

I'm generating content dynamically and in some instances, I need to set a &nbsp; as the only content of a <span> element.

However, the following adds &nbsp; as text vs adding a empty space:

var foo = document.createElement("span")
foo = document.createTextNode("&nbsp;");

which makes sense, so I'm wondering, how would I add &nbsp; correctly without (!) using innerHTML

Thanks for help!

like image 792
frequent Avatar asked Nov 06 '13 10:11

frequent


People also ask

How do I add a non-breaking space in JavaScript?

To add real spaces to your text, you can use the &nbsp; character entity. Tip: The non-breaking hyphen (&#8209;) is used to define a hyphen character (‑) that does not break into a new line.

How do I create a white space in JavaScript?

Use &nbsp; It is the entity used to represent a non-breaking space.

How do you keep a space in JavaScript?

var text = text. replace(/\s/g, '&nbsp;'); \s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.


2 Answers

You can use a unicode literal for a non breaking space:

var foo = document.createTextNode("\u00A0");
like image 75
vcsjones Avatar answered Oct 24 '22 03:10

vcsjones


If you don't want to use innerHTML, you can use a hexadecimal escape.

The most common:

  • \x20 – standard space or \s
  • \xC2\xA0 – non-breaking space or &nbsp;
  • \x0D – carriage return or \r
  • \x0A – newline or \n
  • \x09 – tab or \t

In your case: \xC2\xA0

like image 14
CodeFanatic Avatar answered Oct 24 '22 02:10

CodeFanatic