javascript - 用字符串替换空格

0 javascript

我是Javascript的新手,需要对大学课程中的程序提供一些帮助,用字符串"spaces"替换字符串中的所有空格.

我使用了以下代码,但我无法让它工作:

<html>
<body>
<script type ="text/javascript">
// Program to replace any spaces in a string of text with the word "spaces".
var str = "Visit Micro soft!";

var result = "";

For (var index = 0; index < str.length ; index = index + 1)
{ 
    if (str.charAt(index)= " ")
    {
        result = result + "space";

    }
    else
    { 
        result = result + (str.charAt(index));

    }

}   

document.write(" The answer is " + result );
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)