nodejs 字符串格式化
时间: 2023-07-21 09:12:02 浏览: 48
在 Node.js 中,可以使用 `util.format()` 方法来进行字符串格式化。`util.format()` 方法的使用方式与 Python 中的 `str.format()` 方法类似。
例如,可以使用以下代码将一个整数和一个字符串插入到另一个字符串中:
```
const util = require('util');
const num = 42;
const name = "Alice";
const message = util.format("Hello, my name is %s and my favorite number is %d.", name, num);
console.log(message);
```
输出结果为:
```
Hello, my name is Alice and my favorite number is 42.
```
在格式化字符串中,用 `%s` 表示字符串类型的占位符,用 `%d` 表示整数类型的占位符。在 `util.format()` 方法中,将需要插入到占位符位置的值按顺序传入即可。也可以在格式化字符串中使用多个占位符,并且可以使用命名参数来指定需要插入的值。例如:
```
const util = require('util');
const num = 42;
const name = "Alice";
const date = "2021-01-01";
const message = util.format("Hello, my name is %s and my favorite number is %d. Today is %s.", name, num, date);
console.log(message);
```
输出结果为:
```
Hello, my name is Alice and my favorite number is 42. Today is 2021-01-01.
```