迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中获取字符串的最后 N 个字符

作者:迹忆客 最近更新:2022/12/13 浏览次数:

要获取字符串的最后 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);

JavaScript 中获取字符串的最后 N 个字符

我们传递给 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.substringString.slice 之间的其他差异,请查看 MDN 文档

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便