title: How can spaces be converted to &nbsp without breaking HTML tags?
body: <p>I've inherited some pretty complex code for a web forum, and one of the features I'm trying to implement is the ability for spaces to not be truncated into only one. This is mainly because our users often want to include ASCII art, tables etc in their posts.</p>
  
  <p>I first did this using a simple search and replace in javascript, which had the side effect of breaking HTML tags (eg <code>&lt;a href=....&gt;</code> became <code>&lt;a&amp;nbsp;href=.....&gt;</code>).</p>
  
  <p>I then tried doing this on server side, when the strings are retrieved, by having spaces converted before links and code people insert is converted to HTML. This works to a degree but it causes some issues with other parts of the code, for example where a message is truncated to appear on the home page, it might leave some of the space code, such as</p>
  
  <blockquote>
    <p>Here is a message&amp;nb</p>
  </blockquote>
  
  <p>I think there may be a way to just alter the original javascript to achieve this - it just needs to only match spaces that are not inside a HTML tag.</p>
  
  <p>The script I was using originally was <code>message = message.replace(/\s/g, "&amp;nbsp;")</code>.</p>
  
  <p>Thanks for any help you can provide with this.</p>