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 OverflowJava: format Javascript code - Stack Overflow
javascript - How to format a JS script? - Stack Overflow
JavaScript equivalent to printf/String.Format - Stack Overflow
How to format long JavaScript object so that it is split into multiple lines?
Videos
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.
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
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.
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}