2014-01-22 87 views
-1

此代碼似乎仍然不起作用。它沒有錯誤了,但它只返回像這樣的空白括號{}。它應該將str中的每個字母轉換成下一個字母,並將每個元音大寫。有任何想法嗎?字母→下一個字母和大寫元音

function LetterChanges(str) { 
str = str.split("");//split() string into array 
    for(var i=0;i<str.length;i++){//for loop that checks each letter 
    if(str[i].match(/[a-y]/i)){ 
     str[i]=String.fromCharCode(str[i].charCodeAt(0)+1); 
     }else if(str[i].match("z")){ 
      str[i] = "a"; 
     } 
    if(str[i].match(/[aeiou]/i)){ 
     str[i] = str[i].toUpperCase(); 
     } 

    } 
    str = str.join(""); 
    //modifies letter by adding up in alphabet 
    //capitalizes each vowel 
    //join() string 


    return str; 
} 
+2

似乎工作很好 - > http://jsfiddle.net/4eNTJ/,你怎麼用它? – adeneo

回答

1

它看起來是這樣的方法可以通過簡化爲只打了幾個電話給.replace

function LetterChanges(str) { 
    return str 
     .replace(/[a-y]|(z)/gi, function(c, z) { return z ? 'a' : String.fromCharCode(c.charCodeAt(0)+1); }) 
     .replace(/[aeiou]/g, function(c) { return x.toUpperCase(); }); 
} 

LetterChanges("abcdefgxyz"); 
//   "bcdEfghyzA" 

或者,一個調用.replace,像這樣:

function LetterChanges(str) { 
    return str.replace(/(z)|([dhnt])|[a-y]/gi, function(c, z, v) { 
     c = z ? 'A' : String.fromCharCode(c.charCodeAt(0)+1); 
     return v ? c.toUpperCase() : c; 
    }) 
} 

LetterChanges("abcdefgxyz"); 
//   "bcdEfghyzA" 
相關問題