Search code examples
javascripthtmlcode-snippetsprettify

How to display properly formatted JS code snippets on a web page?


I am storing a JavaScript function in DB without spaces. Later I am retrieving from DB and showing on a Web page using google prettify but the code-snippet shows in a single line,

var Pizza = function(size, toppingCodes) {
  this.size = size;
  this.toppingCodes = toppingCodes;
  this.toString = function() {
    return "A " + size + " pizza with " + this.toppingCodes + ".";
  };
};
Pizza.prototype.getBaseCost = function() {
  switch (this.size) {
    case "small":
      return 6.50;
    case "medium":
      return 7.50;
    case "large":
      return 8.50;
  }
};

I am getting the key-word color etc by using google prettify. Can I show the above JS function in a nicely formatted way. DO we have a tool/library for this ??


Solution

  • I finally figured it out. when saving into database, I need to encode it using encodeURI(string) and when fetch from the server back, I need to decode it using decodeURI(string).