如何移除字符串末尾字符并移至开头,或实现字符串反转?
解决方案
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
相关产品推荐
相关产品推荐

