仅从 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
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短