You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除字符串末尾字符并移至开头,或实现字符串反转?

解决方案

1. 将移除的末尾字符移至字符串开头

你原来的代码仅截取了除最后一个字符外的部分,要实现把移除的字符放到开头,需要先单独提取出最后一个字符,再和截取后的部分拼接:

const str = "Hello world";
const lastChar = str.slice(-1); // 获取最后一个字符 'd'
const remainingStr = str.slice(0, -1); // 截取除最后一个字符外的部分 'Hello worl'
const result1 = lastChar + remainingStr; // 拼接得到 'dHello worl'
console.log(result1); // 输出: dHello worl

也可以用一行代码简化:

const str = "Hello world";
const result1 = str.slice(-1) + str.slice(0, -1);

2. 实现字符串整体反转

如果是要把整个字符串完全反转(比如 "Hello world" 变成 "dlrow olleH"),可以通过字符串转数组、反转数组再转回字符串的方式实现:

const str = "Hello world";
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // 输出: dlrow olleH

如果你的需求是把空格分隔的两部分调换顺序(得到 "world Hello"),可以这样处理:

const str = "Hello world";
const reversedParts = str.split(' ').reverse().join(' ');
console.log(reversedParts); // 输出: world Hello

内容的提问来源于stack exchange,提问作者Web_dev_Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:02:42