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> 
2
  • 2
    you if statement needs a == instead of an =. == is for comparison and = is for saving things inside of variables (assignment) Commented Sep 23, 2011 at 13:53
  • 2
    In what way does it 'not work'? Commented Sep 23, 2011 at 13:53

5 Answers 5

5
For 

isn't capitalized:

for 

and

str.charAt(index)= " " 

needs to be:

str.charAt(index) == " " 

JavaScript Comparison Operators

for loops

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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
@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...
1

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

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

Comments

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

2 Comments

That will only replace the first instance of the space character.
That will only replace the first space.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.