2016-02-19 83 views
0

我如何使它的功能將採取參數(品種)和搜索大寫字母,並在那裏添加一個空間。如何使一個函數,找到一個字符串中的大寫字母,並添加一個空格

例如,如果我通過「金毛尋回犬」作爲帕拉姆,則該函數將其轉化爲「金毛」

function test(breed){ 
    for(i=1; i<breed.length; i++){ 
    //wat do i do here 
    } 
} 
+0

這聽起來像是給我一份家庭作業。嘗試搜索,我會開始你的第一個解決方案:http://stackoverflow.com/questions/1027224/how-can-i-test-if-a-letter-in-a-string-is-uppercase- or-lowercase-using-javascrip – Duniyadnd

+0

當使用正則表達式的.replace()可以實現時,我不會使用循環。 – nnnnnn

回答

5

您使用正則表達式與positive lookahead/(?=[A-Z])/每個大寫字母還沒來得及split the string ,那麼你可以用空格加入串到一起,並將其轉換爲小寫:

"goldenRetrieverDog".split(/(?=[A-Z])/).join(' ').toLowerCase(); 
// "golden retriever dog" 

或者,您也可以使用.replace() method每個前添加一個空格大寫字母,然後將字符串轉換爲小寫字母:

"goldenRetrieverDog".replace(/([A-Z])/g, " $1").toLowerCase(); 
// "golden retriever dog" 
+0

@ Firefalcon1155因爲你沒有返回字符串。它應該是'return breed.split(/(?= [A-Z])/)。join('').toLowerCase();'..看到這個例子 - > https://jsfiddle.net/L7m2x7uL/ –

相關問題