将字符串大写字母移动到前面,同时保持相对顺序 - JavaScript
我们需要编写一个 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP