Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Đảo ngược chỉ phụ âm trong chuỗi bằng JavaScript


Vấn đề

Cần viết hàm JS nhận chuỗi chữ thường. Trả về chuỗi mới với thứ tự phụ âm đảo ngược, nguyên âm giữ nguyên vị trí.

Ví dụ:

const str = 'somestring';

Kết quả:

const output = 'gomenrtiss';

Ví dụ

Mã thực hiện:

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));

Kết quả

Kết quả in ra console:

gomenrtiss