Skip to content

Instantly share code, notes, and snippets.

@tonysamperi
Created September 20, 2018 14:44
Show Gist options
  • Save tonysamperi/d44ba59b6dff5f79fe0670dee9d24795 to your computer and use it in GitHub Desktop.
Save tonysamperi/d44ba59b6dff5f79fe0670dee9d24795 to your computer and use it in GitHub Desktop.
Javascript sprintf
/**
* Returns a formatted string using the first argument as a printf-like format.
*
* The first argument is a string that contains zero or more placeholders.
* Each placeholder is replaced with the converted value from its corresponding argument.
*
* Supported placeholders are:
*
* %s - String.
* %d - Number (both integer and float).
* %% - single percent sign ('%'). This does not consume an argument.
*
* Argument swapping:
*
* %1$s ... %n$s
*
* When using argument swapping, the n$ position specifier must come immediately
* after the percent sign (%), before any other specifiers, as shown in the example below.
*
* If the placeholder does not have a corresponding argument, the placeholder is not replaced.
*
* @author odan
*
* @param {...*} format [, args [, ...*]
* @returns {String}
*/
sprintf() {
if (arguments.length < 2) {
return arguments[0];
}
let index = 1;
const result = (args[0] + "").replace(/%((\d)\$)?([sd%])/g, function (match, _group_, pos, _format_) {
if (match === "%%") {
return "%";
}
if (typeof pos === "undefined") {
pos = index++;
}
if (pos in args && pos > 0) {
return args[pos];
} else {
return match;
}
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment