我是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>
答案 0 :(得分:5)
答案 1 :(得分:1)
正如其他人所说,您的代码中存在一些明显的错误:
for
必须全部为小写。=
与比较运算符==
和===
不同。如果您被允许使用库函数,则此问题看起来非常适合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)