0

I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces".

I've used the following code but I just can't get it to work:

<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>
Sean Vieira
  • 148,604
  • 32
  • 306
  • 290

5 Answers5

5
For 

isn't capitalized:

for

and

str.charAt(index)= " "

needs to be:

str.charAt(index) == " "

JavaScript Comparison Operators

for loops

Joe
  • 77,580
  • 18
  • 124
  • 143
1

As others have mentioned there are a few obvious errors in your code:

  1. The control flow keyword for must be all lower-case.
  2. The assignment operator = is different than the comparison operators == and ===.

If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function.

maerics
  • 143,080
  • 41
  • 260
  • 285
  • hey now. it's clearly an entry level assignment in an entry level class. If he pulls out regex the teacher will be a bit fishy. :p – Cory Danielson Sep 23 '11 at 13:55
  • @ImportedNoob: true, but I'll bet if you search the internet for "JavaScript string replace" (derived simply from the goal of the homework) you could get yourself to the same place... – maerics Sep 23 '11 at 13:57
1

Try this:

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

Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string

Hope this help

Community
  • 1
  • 1
Simon Arnold
  • 15,214
  • 6
  • 63
  • 84
1

Another option would be to skip the for cycle altogether and use a regular expression:

"Visit Micro soft!".replace(/(\s)/g, '');
Saul
  • 17,666
  • 8
  • 59
  • 87
0

You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop.

Example of replace:

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

The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear.

Example:

var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1
yoozer8
  • 7,194
  • 6
  • 53
  • 88