How to Format/Tidy/Beautify in JavaScript

How to format/beautify HTML, CSS and JavaScript code in core JavaScript?

The examples use nodejs but the library supports browsers too, as stated in the readme.

So add the (js beautify) script tag as mentioned in the readme:

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.0/beautify-js.min.js"></script>

Then you can use the following example code:

const sourceContent = "function test() { ... }";
const beautified = js_beautify(sourceContent);

The web library is mentioned here:
https://github.com/beautify-web/js-beautify/blob/master/README.md#web-library

The available web methods are mentioned here: https://github.com/beautify-web/js-beautify/blob/master/README.md#web-library-1

So yes, you were very close with js-beautify() instead of js_beautify() :)

How can I beautify JavaScript code using Command Line?

First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at http://jsbeautifier.org/, because it's what I found first. Downloads its file https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js

Second, download and install The Mozilla group's Java based Javascript engine, Rhino. "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this

java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js

Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example

//original code    
(function() { ... js_beautify code ... }());

//new code
print(global.js_beautify(readFile(arguments[0])));

Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file.

You'd invoke the above something like

java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js

You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.

How to beautify the html tags using jquery

You can do something like this using javascript Regex:

var htmlstr='<!DOCTYPE html><html lang="en"><head> <style type="text/css"> .attach_btn{font-family: Helvetica,Arial,sans-serif; font-size: 16px; font-weight: 700; color: #fefefe; text-decoration: none; display: inline-block; padding: 8px 16px; border-radius: 3px; background: #243f89; border: none; border-color: #243f89;}p{margin:10px 0; padding:0;}table{border-collapse:collapse;}h1,h2,h3,h4,h5,h6{display:block; margin:0; padding:0;}img,a img{border:0; height:auto; outline:none; text-decoration:none;}body,#bodyTable,#bodyCell{height:100%; margin:0; padding:0; width:100%;}.mcnPreviewText{display:none !important;}#outlook a{padding:0;}img{-ms-interpolation-mode:bicubic;}table{mso-table-lspace:0pt; mso-table-rspace:0pt;}<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Purple Admin</title> <link rel="stylesheet" href="vendors/iconfonts/mdi/css/materialdesignicons.min.css"> <link rel="stylesheet" href="vendors/css/vendor.bundle.base.css"> <link rel="stylesheet" href="css/style.css"> <link rel="shortcut icon" href="images/favicon.png"/></head><body> <div class="container-scroller"> </body></html>';
htmlstr = htmlstr.split(/\>[ ]?\</).join(">\n<");
htmlstr = htmlstr.split(/([*]?\{|\}[*]?\{|\}[*]?)/).join("\n");
htmlstr = htmlstr.split(/[*]?\;/).join("\;\n ");
document.body.innerText= htmlstr;

Is copy-and-paste coding ever acceptable?

I've heard people say the will copy and paste once (limiting duplication of code to at most two instances), as abstractions don't pay off unless you use the code in three places or more. () Myself, I try to make it a good habit of refactoring as soon as I see the need.

Beautifly / Tidy (Javascript) in Visual Studio Code

If you want to beautify the code you can just press
ctrl+shift+p and type format code or press alt+shift+f

It correctly indents my code so it seems like that is what you looking for, if not you might want to give an example.

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

How to correct indentation in HTML string?

Here is a simple recursive function I wrote, which I think might help you to achieve what you are after.

function process(str) {

var div = document.createElement('div');
div.innerHTML = str.trim();

return format(div, 0).innerHTML;
}

function format(node, level) {

var indentBefore = new Array(level++ + 1).join(' '),
indentAfter = new Array(level - 1).join(' '),
textNode;

for (var i = 0; i < node.children.length; i++) {

textNode = document.createTextNode('\n' + indentBefore);
node.insertBefore(textNode, node.children[i]);

format(node.children[i], level);

if (node.lastElementChild == node.children[i]) {
textNode = document.createTextNode('\n' + indentAfter);
node.appendChild(textNode);
}
}

return node;
}

Then you would use it like this:

process(str);

Here is a demo:

var str = '<div id="a"><span class="b"><span>Hello</span></span><input type="text"><p><b>b <i>italic</i></b></p></div>';
function process(str) { var div = document.createElement('div'); div.innerHTML = str.trim();
return format(div, 0).innerHTML;}
function format(node, level) { var indentBefore = new Array(level++ + 1).join(' '), indentAfter = new Array(level - 1).join(' '), textNode;
for (var i = 0; i < node.children.length; i++) { textNode = document.createTextNode('\n' + indentBefore); node.insertBefore(textNode, node.children[i]);
format(node.children[i], level);
if (node.lastElementChild == node.children[i]) { textNode = document.createTextNode('\n' + indentAfter); node.appendChild(textNode); } }
return node;}
document.querySelector('#out').innerText = process(str);
<pre id="out"></pre>


Related Topics



Leave a reply



Submit