迹忆客 专注技术分享

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

在 JavaScript 中根据字符串的最后一次出现进行拆分

作者:迹忆客 最近更新:2023/01/21 浏览次数:

要在最后一次出现的子字符串上拆分字符串:,使用 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 方法。否则,前后变量将存储空字符串。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便