仅从 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