title: How can I ensure text is valid for an SVG?
body: <p>When I include a non-breaking space (character encoded as <code>\u00A0</code>) in an SVG <code>text</code> element, it works fine on a HTML page, but the resulting SVG contains an <code>&amp;nbsp;</code> character and is therefore not valid as an SVG file. For example, if I save the SVG to a file (using a <a href="https://stackoverflow.com/a/38019175/567595">function like this</a>) and open that file in Chrome, it reports an error &quot;Entity 'nbsp' not defined&quot; and does not display the text.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const NS = { SVG: "http://www.w3.org/2000/svg" };
  const svg = document.createElementNS(NS.SVG, 'svg');
  const text = document.createElementNS(NS.SVG, "text");
  text.setAttribute("y", 20);
  const s = "Non-breaking&gt; &lt;space"; // the space here is a non-breaking one
  text.appendChild(document.createTextNode(s));
  svg.appendChild(text);
  document.body.appendChild(svg);
  console.log(svg.outerHTML);</code></pre>
  </div>
  </div>
  </p>
  <p>I can easily replace the problematic character with <code>s.replace(&quot;\u00A0&quot;, &quot; &quot;)</code>. But is there a more general way of sanitizing text going into an SVG to ensure it is valid and replacing the non-valid characters?</p>