将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
1 var test1 = "We Are Happy"; //注意:这三个相邻的字符串,相邻间只有一个空格 2 console.log(test1.replace(/s+/g, "%20")); //输出We%20Are%20Happy 3 //可以解决相邻间只有一个空格的情况,但是不符合题意 4 5 // 现在将test改为 6 var test2 = "We Are Happy"; //注意:We和Are之间有2个空格 7 console.log(test2.split(" ").join("%20")); //输出We%20%20Are%20Happy 8 //split方法将数组分成了["We","","Are","Happy"];所以每一个空格都能被改为"%20"