Design & Download
Your JS Library
in Seconds!!!

Snippet: htmlify()

Written by Christopher West (cwest) on November 07, 2015.
Converts a normal string into a string that can be treated as raw HTML.
function htmlify(str, opt_keepWhitespace) {
  str = str.replace(/&/g, '&')
           .replace(/</g, '&lt;')
           .replace(/>/g, '&gt;')
           .replace(/"/g, '&quot;')
           .replace(/'/g, '&#x27;')
           .replace(/`/g, '&#x60;');
  return opt_keepWhitespace
    ? str.replace(/\r?\n|\r/g, '<br />')
         .replace(/\t/g, '    ')
         .replace(/^ | (?= )| $/g, '&nbsp;')
    : str;
}

At times we need to be able to convert a normal string into a string that can be treated as raw HTML. That is where htmlify() comes in handy.

Parameters

  1. str {string}:
    The string to be converted to raw HTML.
  2. optKeepWhitespace {boolean}:
    Optional. Defaults to false. If set to true the returned string will convert multiple, consecutive spaces to non-breaking spaces followed by one normal space. If set to true, line breaks will be converted to <br />.

Returns

The converted string is returned.