迹忆客 专注技术分享

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

在 JavaScript 中从字符串中删除最后一个字符

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

在某些情况下,我们必须从字符串中修剪/截断/删除一个字符。由于 JavaScript 中的字符串是不可变的,我们不能修改现有的字符串,但我们必须创建一个具有所需更改的新字符串。我们可以使用各种方法删除最后一个字符,例如正则表达式、获取不包括最后一个字符的子字符串等。我们将看到从 JavaScript 字符串中删除最后一个字符的不同方法。

我们使用 substring() 方法返回两个索引之间的字符串部分。如果仅提供一个索引,则将其视为起始索引,该函数返回该字符串从起始索引到最后一个索引的子字符串。要仅从字符串中删除最后一个字符,我们必须将结尾索引提供为 len - 1,其中 len 是字符串的长度。由于 len-1 是字符串的最后一个索引,我们希望该字符串位于该索引处的字符之前。

const str = "DelftStacks";
const str2 = str.substring(0, str.length - 1);
console.log(str2);

输出:

DelftStack

类似于 substring() 的函数是 substr();它也需要两个参数,但在 substr() 的情况下,第二个参数是子字符串的长度。我们可以通过以下代码使用它来实现相同的结果。

const str = "DelftStacks";
const str2 = str.substr(0, str.length - 1);
console.log(str2);

输出:

DelftStack

虽然它等同于 substring 方法,但仍然避免使用,因为它被认为是遗留方法,使用 substring() 方法更可取。

slice() 方法的工作原理与 substring() 方法非常相似。它还采用起始索引 start_index 和结束索引 end_index 作为参数。显着的区别是我们可以在函数中使用负索引作为参数。通过添加值 str.length 将负索引带入正常范围。我们可以通过传递 0 作为起始索引和 -1 作为结束索引来切掉最后一个字符。

const str = "DelftStacks";
const str2 = str.slice(0, -1);
console.log(str2);

输出:

DelftStack

我们还可以使用 replace() 函数从字符串中删除最后一个字符。它接受一个正则表达式作为输入并替换正则表达式的结果。$ 字符用于匹配输入的结尾。. 用于匹配单个字符。因此,正则表达式 /.$/ 可用于从字符串中获取最后一个字符。在此之后,我们将其替换为 '',即空白,以将其从字符串中删除。

const str = "DelftStacks";
const str2= str.replace(/.$/, '');
console.log(str2);

输出:

DelftStack

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

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便