**题目:**请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy。则经过替换之后的字符串为We%20Are%20Happy
**思路:**创建一个新的空的字符串,如果遇到空格就把%20插入新的字符串中,否则就把遇到的字符插入的新的字符串,最后返回新的字符串。
<!-- 请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.
则经过替换之后的字符串为We%20Are%20Happy。 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function replaceSpace(str) {
// write code here
var n = str.length;
//创建一个空的字符串
var newstr = '';
//遍历数组
for (var i = 0; i < n; i++) {
//如果遇到空格,则把%20加入到新字符串中
if (str[i] == ' ')
newstr += "%20";
//否则就把遇到的字符加入到新字符串中
else
newstr += str[i];
}
return newstr;
}
var str = "hello world";
console.log(replaceSpace(str));
</script>
</body>
</html>