user7217977
user7217977

Reputation:

JavaScript: String isn't concating like I expect

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

    }

Upvotes: 1

Views: 58

Answers (2)

Joseph Marikle
Joseph Marikle

Reputation: 78590

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

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 82088

It's because you're looping twice but only adding the ay once. Because the starts with two consonants, the h is pushed to the end at the second iteration.

str = "the extra quick brown fox"
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].substring(0,1);
            }
        }
        console.log(str[i])

        str[i] = str[i] + 'ay';
        console.log(str)
    }
    str = str.join(" ");

}
VM383:12 het
// Notice it is correct with the first pass.
VM383:15 (5) ["hetay", "extra", "ickqu", "rownb", "oxf"]
VM383:12 extra
// but it is incorrect after the second.
VM383:15 (5) ["etayh", "extraay", "ickqu", "ownbr", "oxf"]

Upvotes: 0

Related Questions