📜  Node.js substr()函数(1)

📅  最后修改于: 2023-12-03 15:03:14.339000             🧑  作者: Mango

Node.js substr()函数

在Node.js中,可以使用substr()函数来截取字符串中的一部分。

语法
str.substr(start[, length])

参数说明:

  • start:必需,表示切割开始位置的下标。如果是负数,那么从字符串的末尾开始计算。
  • length:可选,表示要截取的长度。如果省略,则截取到字符串末尾。
返回值

substr()函数会返回从 start 开始、长度为 length 的字符串。

示例

例如,现在有一个字符串 hello world,我们可以使用以下代码获取前5个字符:

const str = 'hello world';
const s = str.substr(0, 5);
console.log(s); // 输出结果为: "hello"

同样的,如果我们想获取后5个字符,可以使用以下代码:

const str = 'hello world';
const s = str.substr(-5);
console.log(s); // 输出结果为: "world"

如果省略第二个参数,那么将会截取到字符串末尾:

const str = 'hello world';
const s = str.substr(6);
console.log(s); // 输出结果为: "world"
注意事项

请注意,在使用 substr() 函数时,如果第一个参数指定了一个越界的下标,那么将会返回一个空字符串。

const str = 'hello world';
const s = str.substr(100);
console.log(s); // 输出结果为: ""

因此,在使用 substr() 函数时,请确保传递正确的参数,以避免出现潜在的错误。