JavaScript 中获取字符串的前 N 个字符
使用 String.slice()
方法获取字符串的前 N 个字符,例如 str.slice(0, 3)
。 slice()
方法将 start 和 stop 索引作为参数,并返回一个包含原始字符串切片的新字符串。
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.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 中合并两个数组,以及如何删除任何重复的数组。