JavaScript sprintf
is a function that is commonly used in other programming languages, but is not built into JavaScript itself. It allows you to format strings using placeholders, similar to the printf
function in C.
The sprintf
function takes a format string and one or more values as arguments, and returns a string with placeholders replaced by the corresponding values. The placeholders are specified using a special syntax, which includes a percent sign (%
) followed by one or more format specifiers.
JavaScript sprintf example
Simple example code creates sprintf
with similar functionality using the String.prototype.replace()
method and regular expressions.
<!DOCTYPE html>
<html>
<head>
<script>
function sprintf(format, ...args) {
let index = 0;
return format.replace(/%s/g, () => args[index++]);
}
const name = 'John';
const age = 30;
const message = sprintf('My name is %s and I\'m %s years old.', name, age);
console.log(message);
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version