Skip to content
DeveloperMemos

Using sprintf in Deno

Deno, sprintf, string formatting1 min read

String formatting is a common task in programming, and it's often necessary to construct strings dynamically by substituting placeholders with corresponding values. While there are many ways to achieve this, one popular method is to use the sprintf function.

In this article, we'll explore how to use the sprintf function in Deno, which is a modern runtime for JavaScript and TypeScript.

What is sprintf?

The sprintf function is a C library function that formats and writes data to a string buffer. It takes a format string as its first argument, which can contain placeholders marked with %, followed by one or more arguments that correspond to the placeholders.

Here's a simple example:

1import { sprintf } from "https://deno.land/std/fmt/printf.ts";
2
3const name = 'John';
4const age = 30;
5
6const message = sprintf('My name is %s and I am %d years old.', name, age);
7
8console.log(message);
9// Output: My name is John and I am 30 years old.

In this example, we imported the sprintf function from the fmt module of the Deno standard library. We then used it to construct a message string by substituting the %s placeholder with the name variable and the %d placeholder with the age variable.

Supported format specifiers

The sprintf function supports a variety of format specifiers, which are used to specify the type and format of the corresponding argument. Here's a list of some commonly used specifiers:

  • %s: String
  • %d: Integer
  • %f: Floating point number
  • %b: Binary representation of an integer
  • %o: Octal representation of an integer
  • %x: Hexadecimal representation of an integer (lowercase)
  • %X: Hexadecimal representation of an integer (uppercase)

There are also more advanced specifiers that can be used to control the width, precision, and alignment of the output.

Here's an example that demonstrates some of these specifiers:

1import { sprintf } from "https://deno.land/std/fmt/printf.ts";
2
3const name = 'Mary';
4const balance = 12345.6789;
5
6const message = sprintf('Hello, %s! Your current balance is $%0.2f.', name, balance);
7
8console.log(message);
9// Output: Hello, Mary! Your current balance is $12345.68.

In this example, we used the %s specifier to substitute the name variable, and the %0.2f specifier to substitute the balance variable with two decimal places.

In Closing

In this article, we learned how to use the sprintf function in Deno for string formatting. We covered the basics of using placeholders and format specifiers to construct dynamic strings, and provided some examples to demonstrate their usage. While there are many other ways to achieve string formatting, sprintf remains a popular choice due to its flexibility and familiarity among developers. If you're working with Deno, be sure to give it a try!