Skip to content

Instantly share code, notes, and snippets.

@sandipransing
Created October 10, 2013 07:56
Show Gist options
  • Select an option

  • Save sandipransing/6914650 to your computer and use it in GitHub Desktop.

Select an option

Save sandipransing/6914650 to your computer and use it in GitHub Desktop.
jQuery extension to have `simple_format` function just like we have in `rails`. jquery ".html(text)" method ignores \n (newline) chars that can be solved here. simpleFormat will replace newline chars with line breaks.
// **Example Usage**
// $.simpleFormat("this is first \n here is next line")
// OR
// $(".note").simpleFormat()
(function($) {
$.simpleFormat = function(str) {
str = str.replace(/\r\n?/, "\n");
str = $.trim(str);
if (str.length > 0) {
str = str.replace(/\n\n+/g, "</p><p>");
str = str.replace(/\n/g, "<br />");
str = "<p>" + str + "</p>";
}
return str;
};
$.fn.simpleFormat = function() {
return this.html($.simpleFormat(this.html()));
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment