将字符串大写字母移到前面并保持相对顺序 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 17:16:17
我们需要编写一个 JavaScript 函数,该函数接受一个包含大写和小写字母的字符串。该函数应返回一个字符串,其中所有大写字母都移到了字符串的前面。
例如:如果输入字符串是 −
const str = 'heLLO woRlD';
那么输出应该是 −
const output = 'LLORDhe wol';
示例
以下是代码 −
const str = 'heLLO woRlD';
const moveCapitalToFront = (str = '') => {
let capitalIndex = 0;
const newStrArr = [];
for(let i = 0; i < str.length; i++){
if(str[i] !== str[i].toLowerCase()){
newStrArr.splice(capitalIndex, 0, str[i]);
capitalIndex++;
}else{
newStrArr.push(str[i]);
};
};
return newStrArr.join('');
};
console.log(moveCapitalToFront(str));
输出
以下是控制台中的输出 −
LLORDhe wol
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

