迹忆客 专注技术分享

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

JavaScript 中获取字符串的前 N 个字符

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

使用 String.slice() 方法获取字符串的前 N 个字符,例如 str.slice(0, 3)slice() 方法将 startstop 索引作为参数,并返回一个包含原始字符串切片的新字符串。

const str = 'Hello World';

const first3 = str.slice(0, 3); // 👉️ Hel
console.log(first3);

const first2 = str.slice(0, 2); // 👉️ He
console.log(first2);

String.slice 方法不会改变原始字符串,它会返回一个新字符串。 字符串在 JavaScript 中是不可变的。

我们传递给 String.slice 方法的第一个参数是起始索引——要包含在新字符串中的第一个字符的索引。

第二个参数是结束索引 - 向上但不包括该字符。

如果您提供给 String.slice 方法的结束索引大于字符串的长度,该方法不会抛出错误,而是返回整个字符串的副本。

const str = 'Hello World';

const first100 = str.slice(0, 100); // 👉️ Hello World
console.log(first100);

我们试图获取仅包含 11 个字符的字符串的前 100 个字符。 结果,slice 方法返回了整个字符串。

String.substring 方法也可用于获取字符串的前 N 个字符,但是 String.slice 使用起来更加灵活和直观。

如果我们想了解 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便