Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 字符串去掉最后一个字符

作者:战虎天下   发布日期:2026-04-22   浏览:65

// 示例代码:去掉字符串的最后一个字符

function removeLastChar(str) {
    // 检查字符串是否为空或长度为1,如果是则返回空字符串
    if (str.length <= 1) {
        return '';
    }
    // 使用 substring 方法去掉最后一个字符
    return str.substring(0, str.length - 1);
}

// 示例用法
let originalString = "hello";
let newString = removeLastChar(originalString);
console.log(newString); // 输出: "hell"

解释说明:

  • removeLastChar 函数接收一个字符串 str 作为参数。
  • 如果字符串长度小于等于 1,则直接返回空字符串(因为去掉最后一个字符后没有意义)。
  • 否则,使用 substring 方法从索引 0 开始到倒数第二个字符(即 str.length - 1),从而去掉最后一个字符。
  • 最后通过示例用法展示了如何调用该函数并输出结果。

上一篇:js 查找字符串中是否包含字符

下一篇:js 获取字符串第一个字符

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站