JavaScript:字符串不像我期望的那样简明扼要

时间:2018-06-20 19:35:29

标签: javascript regex string concatenation string-concatenation

输入:“棕色狐狸”

预期结果:“ ethay ickquay ownbray oxfay”
实际结果:“ etayh ickquay ownbray oxfay”

由于某种原因,只有第一个单词被弄乱了。

代码

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

    }

2 个答案:

答案 0 :(得分:1)

您并没有在substring/slice块中抓住所有辅音。更改您的正则表达式,使其包含所有辅音,然后使用该结果的长度正确切分字符串。

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

答案 1 :(得分:0)

这是因为您要循环两次,但只添加一次ay。因为the以两个辅音开头,所以h在第二次迭代时被推到末尾。

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"]