How do I format my string in GWT?
I made a method
Formatter format = new Formatter();
int matches = 0;
Formatter formattedString = format.forma
Another suggestion which makes use of JSNI and a nice JavaScript format function from another post:
import com.google.gwt.core.client.JsArrayString;
public abstract class StringFormatter {
public static String format(final String format, final Object... args) {
if (null == args || 0 == args.length)
return format;
JsArrayString array = newArray();
for (Object arg : args) {
array.push(String.valueOf(arg)); // TODO: smarter conversion?
}
return nativeFormat(format, array);
}
private static native JsArrayString newArray()/*-{
return [];
}-*/;
private static native String nativeFormat(final String format, final JsArrayString args)/*-{
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
}-*/;
}
One can then make a call like this:
StringFormatter.format("Greetings {0}, it's {1} o'clock, which is a {2} statement", "Master", 8, false);
...with the result being
Greetings Master, it's 8 o'clock, which is a false statement
There is a potential to improve further at the TODO comment, e.g. utilise NumberFormat. Suggestions are welcome.