It may be too late, but still.

I haven't found popular Java libraries for doing what you want; however, there are many javascript libraries for that (for example, js-beautify). You can save such library source code in resources of your application (you can get the code from one of cdn links, so you don't have to group and minify it manually), and then load it and invoke it with the Nashorn javascript engine.

Your code may look like this (roughly):

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStreamReader;

public class JavascriptBeautifierForJava {

    // my javascript beautifier of choice
    private static final String BEAUTIFY_JS_RESOURCE = "beautify.js";

    // name of beautifier function
    private static final String BEAUTIFY_METHOD_NAME = "js_beautify";

    private final ScriptEngine engine;

    JavascriptBeautifierForJava() throws ScriptException {
        engine = new ScriptEngineManager().getEngineByName("nashorn");

        // this is needed to make self invoking function modules work
        // otherwise you won't be able to invoke your function
        engine.eval("var global = this;");
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(BEAUTIFY_JS_RESOURCE)));
    }

    public String beautify(String javascriptCode) throws ScriptException, NoSuchMethodException {
        return (String) ((Invocable) engine).invokeFunction(BEAUTIFY_METHOD_NAME, javascriptCode);
    }

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        String unformattedJs = "var a = 1; b = 2; var user = { name : \n \"Andrew\"}";

        JavascriptBeautifierForJava javascriptBeautifierForJava = new JavascriptBeautifierForJava();
        String formattedJs = javascriptBeautifierForJava.beautify(unformattedJs);

        System.out.println(formattedJs);
        // will print out:
        //        var a = 1;
        //        b = 2;
        //        var user = {
        //            name: "Andrew"
        //        }
    }
}

If you're going to use this approach, make sure to reuse JavascriptBeautifier object, because it's not too effective to recreate one whenever you need to beautify code.

Answer from Roman Golyshev on Stack Overflow
🌐
Beautifier
beautifier.io
Online JavaScript beautifier
Sublime Text 2: JsFormat, a javascript formatting plugin for this nice editor by Davis Clark,
🌐
JSON Formatter
jsonformatter.org › jsbeautifier
Best JSBeautifier to beautify / format JavaScript
This Javascript Beautifier that supports indentation levels: 2 tab spaces, 3 tab spaces, and 4 tab spaces. Download JS, once it's formatted, created or modified and this js file can be opened in Sublime, VSCode, and Notepad++ alternative.
Discussions

Java: format Javascript code - Stack Overflow
In my architecture Javascript code is generated in the server. A huge chunk of Javascript code is generated, stored in a java.lang.String and sent to the client side. I want to more easily debug the More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to format a JS script? - Stack Overflow
I have a simple question I am an ethical hacker and I want to see and discover a fake website. I want to see a JS script from an HTML usually this script is externally put from some website. like More on stackoverflow.com
🌐 stackoverflow.com
JavaScript equivalent to printf/String.Format - Stack Overflow
I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET). My basic requirement is a thousand separator format for n... More on stackoverflow.com
🌐 stackoverflow.com
How to format long JavaScript object so that it is split into multiple lines?
I finally found the issue. I was pasting the object without assigning it to a variable. The formatter didn't tell me this was the solution: const name = {} More on reddit.com
🌐 r/vscode
1
1
December 10, 2018
🌐
Prettier
prettier.io
Prettier · Opinionated Code Formatter · Prettier
Elm (via elm-format) Java · PHP · Ruby · Rust · TOML · XML · And more... prettier-js prettier.el Apheleia · espresso-prettier · Prettier Prettier⁺ · JsPrettier · vim-prettier neoformat ALE coc-prettier · JavaScriptPrettier · prettier-vscode · Built-in support ·
🌐
GeeksforGeeks
geeksforgeeks.org › utilities › javascript-formatter
Online Free JavaScript Formatter and Beautifier - GeeksforGeeks
1 week ago - Step 1. Input the JavaScript code in the first box. You can write the code, copy and paste it, or upload the JavaScript code file. Step 2. Click on the format button to format JavaScript code.
Top answer
1 of 5
5

It may be too late, but still.

I haven't found popular Java libraries for doing what you want; however, there are many javascript libraries for that (for example, js-beautify). You can save such library source code in resources of your application (you can get the code from one of cdn links, so you don't have to group and minify it manually), and then load it and invoke it with the Nashorn javascript engine.

Your code may look like this (roughly):

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStreamReader;

public class JavascriptBeautifierForJava {

    // my javascript beautifier of choice
    private static final String BEAUTIFY_JS_RESOURCE = "beautify.js";

    // name of beautifier function
    private static final String BEAUTIFY_METHOD_NAME = "js_beautify";

    private final ScriptEngine engine;

    JavascriptBeautifierForJava() throws ScriptException {
        engine = new ScriptEngineManager().getEngineByName("nashorn");

        // this is needed to make self invoking function modules work
        // otherwise you won't be able to invoke your function
        engine.eval("var global = this;");
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(BEAUTIFY_JS_RESOURCE)));
    }

    public String beautify(String javascriptCode) throws ScriptException, NoSuchMethodException {
        return (String) ((Invocable) engine).invokeFunction(BEAUTIFY_METHOD_NAME, javascriptCode);
    }

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        String unformattedJs = "var a = 1; b = 2; var user = { name : \n \"Andrew\"}";

        JavascriptBeautifierForJava javascriptBeautifierForJava = new JavascriptBeautifierForJava();
        String formattedJs = javascriptBeautifierForJava.beautify(unformattedJs);

        System.out.println(formattedJs);
        // will print out:
        //        var a = 1;
        //        b = 2;
        //        var user = {
        //            name: "Andrew"
        //        }
    }
}

If you're going to use this approach, make sure to reuse JavascriptBeautifier object, because it's not too effective to recreate one whenever you need to beautify code.

2 of 5
3

Two closely-related questions (possible duplicates):

  • Command line JavaScript code beautifier that works on Windows and Linux
  • https://stackoverflow.com/questions/6260431/pretty-print-javascript-using-java
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN
Getter function that formats a range of numbers according to the locale and formatting options of the Intl.NumberFormat object from which the method is called.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the date time string format, a simplification of the ISO 8601 calendar date extended format.
🌐
FreeFormatter
freeformatter.com › javascript-beautifier.html
Free Online Javascript Beautifier / Formatter - FreeFormatter.com
Formats JavaScript files with the chosen indentation level and your choice of braces. Supports 4 indentation levels: 2 spaces, 3 spaces, 4 spaces and tabs.
🌐
Code Beautify
codebeautify.org › jsviewer
Best Javascript Beautifier tool work as JavaScript Formatter, Viewer and Prettier
Often the javascript used is provided has white space compressed to reduce the size of the data transferred. This site give you a quick and easy way to format (beautifier) the javascript so you can easily read it.
Top answer
1 of 16
1662

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"

See Kim's answer below for details.


Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneous replacement instead like in fearphage’s suggestion.

2 of 16
1512

Building on the previously suggested solutions:

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

outputs

ASP is dead, but ASP.NET is alive! ASP {2}


If you prefer not to modify String's prototype:

if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
    });
  };
}

Gives you the much more familiar:

String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

with the same result:

ASP is dead, but ASP.NET is alive! ASP {2}

🌐
Static.app
static.app › js-formatter
JS Formatter - Static.app
Format JavaScript code online with our free JS Formatter. Organize and clean up your JavaScript files for better readability and easier maintenance.
🌐
LogRocket
blog.logrocket.com › home › how to format dates in javascript: methods, libraries, and best practices
How to format dates in JavaScript: Methods, libraries, and best practices - LogRocket Blog
May 8, 2025 - While Moment.js was once the go-to library for date handling in JavaScript, it is now considered legacy. The Moment.js team has officially declared the library in maintenance mode and recommends newer alternatives. That said, many existing projects still use it, so it’s worth understanding its approach. ... Let’s look at a typical Moment.js workflow: creating date objects from strings or custom formats, formatting them into readable outputs, adjusting dates by adding or subtracting time, and converting them to specific time zones.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat › format
Intl.NumberFormat.prototype.format() - JavaScript | MDN
July 10, 2025 - A string representing the given number formatted according to the locale and formatting options of this Intl.NumberFormat object.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-format-a-date-with-javascript-date-formatting-in-js
How to Format a Date with JavaScript – Date Formatting in JS
November 7, 2024 - This is why we need to format dates so we can extract what we need from this date object. In JavaScript, there is no direct syntax that provides you with your expected format because date format varies based on location, circumstance, and so on.
🌐
Visual Studio Code
code.visualstudio.com › docs › languages › javascript
JavaScript in Visual Studio Code
November 3, 2021 - VS Code's built-in JavaScript formatter provides basic code formatting with reasonable defaults.
🌐
DebugBear
debugbear.com › tool › beautify-js
Online JavaScript Beautifier: Format JS Code
Prettify JavaScript code to make it easier to read and analyze minified JavaScript files.
🌐
Codecademy
codecademy.com › article › javascript-date-format
How to Format a Date in JavaScript | Codecademy
In JavaScript, the Date() constructor returns a new Date object representing the current date or a specific date. If we create a Date object without any input parameters, it contains the current date and time along with the timezone details. To get a Date object for a specific date, we can pass the date as a string to the Date() constructor. ... You can pass the input date string to the Date() constructor in other formats as well, such as January 14, 2025 or 2025-01-14.
🌐
Built In
builtin.com › articles › js-formatting-date
How to Format Dates in JavaScript | Built In
November 12, 2024 - JavaScript offers a variety of ways to format dates, including using the date object, intl.DateTimeFormat and a number of date libraries. Here’s how to use each one.