在 JavaScript 中根据字符串的最后一次出现进行拆分
要在最后一次出现的子字符串上拆分字符串:,使用 lastIndexOf()
方法获取子字符串的最后一个索引,并在字符串上调用 slice()
方法以获取要拆分的子字符串前后的部分。
const str = 'one#two#three';
const lastIndex = str.lastIndexOf('#');
const before = str.slice(0, lastIndex);
console.log(before); // 👉️ "one#two"
const after = str.slice(lastIndex + 1)
我们使用 String.lastIndexOf
方法获取字符串中最后一次出现的哈希值的索引。
lastIndexOf
方法返回所提供子字符串在字符串中最后一次出现的索引,如果子字符串不包含在字符串中,则返回 -1。
下一步是使用 String.slice
方法获取最后一个索引前后的子字符串。
我们将以下 2 个参数传递给 slice 方法:
- start 索引 - 要包含在新字符串中的第一个字符的索引
- end 索引 - 上升到但不包括该索引
为了获取最后一次出现之前的子字符串,我们调用了起始索引为 0 的 slice
方法并向上移动,但不包括最后一次出现的索引。
为了在最后一次出现之后获取子字符串,我们使用单个参数调用 slice()
方法 - 起始索引。
因为我们不想在字符串中包含散列,所以我们将 1 添加到起始索引。
当我们将单个参数传递给 slice
方法时,它会将字符包含到字符串的末尾。
如果需要处理字符串中不包含子串的场景,可以使用
if
语句。
const str = 'one#two#three';
const lastIndex = str.lastIndexOf('#');
let before = '';
let after = '';
if (lastIndex !== -1) {
before = str.slice(0, lastIndex);
after = str.slice(lastIndex + 1);
}
console.log(before); // 👉️ "one#two"
console.log(after); // 👉️ "three"
我们的 if
语句检查 lastIndexOf
方法是否没有返回 -1。
如果没有,则子字符串包含在字符串中,我们可以安全地调用
slice
方法。否则,前后变量将存储空字符串。
相关文章
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
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。