【JS字符串】slice() – 提取字符串的一部分

JavaScript字符串1年前 (2023)发布 admin
1,815 0

在本教程中,您将学习如何使用 JavaScript String slice() 方法从字符串中提取子字符串。

JavaScript String slice() 方法介绍

String.prototype.slice() 方法提取字符串的一部分并将其作为子字符串返回。 下面显示了 slice() 方法的语法:

slice(start, end)

slice() 方法有两个可选参数 start 和 end。

start

start 参数是一个从零开始的索引,该方法在该索引处开始提取。 例如:

const str = ‘Hello’;
const substr = str.slice(3);

console.log({ substr });

输出:

{ substr: ‘lo’ }

【JS字符串】slice() – 提取字符串的一部分

如果 start 为负数,则 slice() 方法从 str.length + start 开始提取。 例如:

const str = ‘Hello’;
const substr = str.slice(-3);

console.log({ substr });

输出:

{ substr: ‘llo’ }

【JS字符串】slice() – 提取字符串的一部分

如果 start 被省略、未定义或不能转换为数字,则 slice() 方法从字符串的开头开始提取:

const str = ‘Hello’;
const substr = str.slice();

console.log({ substr });

输出:

{ substr: ‘Hello’ }

【JS字符串】slice() – 提取字符串的一部分

如果start大于或等于string 的长度,则该slice()方法返回一个空字符串。例如:

const str = ‘Hello’;
const substr = str.slice(5);

console.log({ substr });

输出:

{ substr: ” }

【JS字符串】slice() – 提取字符串的一部分

End

end 是一个从零开始的索引,指定 slice() 方法结束提取之前的位置。 结果字符串将不包含末尾索引处的字符。 例如:

const str = ‘Hello’;
const substr = str.slice(0, 2);

console.log({ substr });

输出:

{ substr: ‘He’ }

【JS字符串】slice() – 提取字符串的一部分

如果 end 为负数,则 slice() 方法将其视为 str.length + end。 例如:

const str = ‘Hello’;
const substr = str.slice(0, -2);

// str.length 5
// str.length + end = 5 + (-2) = 3

console.log({ substr });

如果末尾大于字符串的长度,则 slice() 方法提取到字符串的末尾。 例如:

const str = ‘Hello’;

const substr = str.slice(2, 6);

console.log({ substr });

输出:

{ substr: ‘llo’ }

【JS字符串】slice() – 提取字符串的一部分

如果end省略 、undefined或无法转换为数字,该slice()方法也会提取到字符串的末尾。例如:

const str = ‘Hello’;
const substr = str.slice(3);

console.log({ substr });

输出:

{ substr: ‘lo’ }

【JS字符串】slice() – 提取字符串的一部分

如果 end 被省略、未定义或不能转换为数字,slice() 方法也会提取到字符串的末尾。 例如:

const str = ‘Hello’;
const substr = str.slice(3, 2);

console.log({ substr });

输出:

{ substr: ” }

【JS字符串】slice() – 提取字符串的一部分

JavaScript String slice() 方法实例

以下示例使用该slice()方法获取电子邮件地址的本地部分:

let email = ‘john@example.com’
let localPart = email.slice(0,email.indexOf(‘@’));

console.log(localPart);

输出:

john

程序是怎么运行的:

首先,使用 indexOf() 方法定位 @ 符号。 indexOf() 的返回值用作 slice() 方法的第二个参数。

然后,使用 slice() 方法从字符串的开头提取电子邮件的本地部分,直到 @ 符号之前的字符。

总结

使用 JavaScript String slice() 方法从字符串中提取子字符串。

© 版权声明

相关文章

暂无评论

暂无评论...