Input: "the quick brown fox"
Expected result: "ethay ickquay ownbray oxfay"
Actual result: "etayh ickquay ownbray oxfay"
For some reason, only the first word comes out messed up.
Code
if (str.match(/[ ]/)) {
str = str.split(" ");
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < str.length; j++) {
if (str[j].match(/^[q][u]/)) str[j] = str[j]
.substring(2) + str[j].slice(0, 2);
if (str[j].match(/^[^aeiou]/)) {
str[j] = str[j].substring(1) + str[j].slice(0, 1);
}
}
str[i] = str[i] + 'ay';
}
str = str.join(" ");
}
You aren't grabbing all the consonants in your substring/slice
block. Change your regex to include all consonants and then use the length of that result to properly slice the string.
str = "the quick brown fox".split(" ");
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < str.length; j++) {
if (str[j].match(/^qu/)) str[j] = str[j]
.substring(2) + str[j].slice(0, 2);
if (match = str[j].match(/^[^aeiou]+/)) {
let charCount = match.toString().length;
str[j] = str[j].substring(charCount) + str[j].slice(0, charCount);
}
}
str[i] = str[i] + 'ay';
}
str = str.join(" ");
console.log(str);