在 JavaScript 中获取字符串的最后 N 个字符
要获取字符串的最后 N 个字符,请对字符串调用 slice
方法,传入 -n 作为参数,例如 str.slice(-3)
返回一个包含原始字符串最后 3 个字符的新字符串。
const str = 'Hello World';
const last3 = str.slice(-3); // 👉️ rld
console.log(last3);
const last2 = str.slice(-2); // 👉️ ld
console.log(last2);
我们传递给 String.slice 方法的参数是起始索引。
例如,传递负索引
-3
意味着给我字符串的最后 3 个字符。
这与传递 string.length - 3
作为起始索引相同。
const str = 'Hello World';
const last3 = str.slice(-3); // 👉️ rld
console.log(last3);
const last3Again = str.slice(str.length - 3); // 👉️ rld
console.log(last3Again);
在这两个示例中,我们都告诉 slice
方法将字符串的最后 3 个字符复制到一个新字符串中。
即使我们尝试获取比字符串包含的字符更多的字符,String.slice
也不会抛出错误。 相反,它将返回整个字符串的副本。
const str = 'Hello World';
const last100 = str.slice(-100); // 👉️ Hello World
console.log(last100);
在示例中,我们尝试获取仅包含 11 个字符的字符串的最后 100 个字符。
结果,
slice
方法返回了整个字符串的副本。
我们还可以使用 String.substring
方法获取字符串的最后 N 个字符。
const str = 'Hello World';
// 👇️ using substring
const last3 = str.substring(str.length - 3); // 👉️ rld
console.log(last3);
但是,使用 String.slice
方法更加直观和可读。
例如,如果我们将负参数传递给
String.substring
方法,它会将其视为传递 0,这非常令人困惑。
有关 String.substring
和 String.slice
之间的其他差异,请查看 MDN 文档。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。