仅从 JavaScript 中的字符串中反转辅音
问题
我们要求编写一个 JavaScript 函数,它以一个只包含小写英语字母的字符串作为唯一的参数。
该函数应构造一个新字符串,其中辅音的顺序已反转,元音保持其相对位置。
例如,如果函数的输入为 -
const str = 'somestring';
那么输出应该为 -
const output = 'gomenrtiss';
示例
代码为 -
const str = 'somestring';
const reverseConsonants = (str = '') => {
const arr = str.split("");
let i = 0, j = arr.length - 1;
const consonants = 'bcdfghjklnpqrstvwxyz';
while(i < j){
while(i < j && consonants.indexOf(arr[i]) < 0) {
i++;
}
while(i< j && consonants.indexOf(arr[j]) < 0) {
j--;
}
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
let result = "";
for(let i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
};
console.log(reverseConsonants(str));输出
控制台中的输出将是 -
gomenrtiss
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP