javascript - 用字符串替换空格

时间:2011-09-23 13:49:58

标签: 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>

6 个答案:

答案 0 :(得分:5)

For 

没有大写:

for

str.charAt(index)= " "

需要:

str.charAt(index) == " "

JavaScript Comparison Operators

for loops

答案 1 :(得分:1)

正如其他人所说,您的代码中存在一些明显的错误:

  1. 控制流关键字for必须全部为小写。
  2. 赋值运算符=与比较运算符=====不同。
  3. 如果您被允许使用库函数,则此问题看起来非常适合JavaScript String.replace(regex,str) function

答案 2 :(得分:1)

试试这个:

str.replace(/(\s)/g, "spaces")

或者看看之前对类似问题的回答:Fastest method to replace all instances of a character in a string

希望这个帮助

答案 3 :(得分:1)

另一种选择是完全跳过for周期并使用正则表达式:

"Visit Micro soft!".replace(/(\s)/g, '');

答案 4 :(得分:0)

您应该使用字符串replace方法。不方便,没有replaceAll,但你可以使用循环替换所有。

替换示例:

var word = "Hello"
word = word.replace('e', 'r')
alert(word) //word = "Hrllo"

对您有用的第二个工具是indexOf,它告诉您字符串中字符串的位置。如果字符串没有出现,则返回-1。

示例:

var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1

答案 5 :(得分:0)

如果你的大学课程没有强迫你使用循环,可以在这里找到一个满意的答案:

Replacing spaces with underscores in JavaScript?

(替换_代表'空间')