無參裝飾器
阿新 • • 發佈:2021-08-31
請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。給定的字串長度不超過100。保證字串中的字元為大寫英文字母、小寫英文字母和空格中的一種。
方法一:暴力解法
1 /** 2 * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可 3 * 4 * 5 * @param s string字串 6 * @return string字串 7 */ 8 function replaceSpace( s ) { 9 // write code here 10 let res =''; 11 for(let i = 0;i<s.length;i++){ 12 if(s[i]===' '){ 13 res += '%20'; 14}else{ 15 res+=s[i]; 16 } 17 } 18 return res; 19 } 20 module.exports = { 21 replaceSpace : replaceSpace 22 };
方法二:正則表示式
1 /** 2 * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可 3 * 4 * 5 * @param s string字串 6 * @return string字串 7 */ 8 function replaceSpace( s ) {9 // write code here 10 let reg = new RegExp(' ','g'); 11 return s.replace(reg,'%20'); 12 } 13 module.exports = { 14 replaceSpace : replaceSpace 15 };
方法三:split+join