Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do I insert spaces in between words of a string?

I am working on The Storymaker app in the JavaScript Basics course. I was able to ask the user for input with the prompt command, stored the input in a variable, added that variable to strings to get a longer message, used the alert() method to display a dialog box with text, and write the output to the webpage with document.write(). However, this is the output that I got:

The goodboy ishelping

There is no space in between the words "good" and "boy" and in between "is" and "helping". How can I fix this? Here is the JavaScript code that I typed in story.js:

var noun = prompt("Please enter a noun: "); var adjective = prompt("Please enter an adjective: "); var verb = prompt("Please enter a verb: "); var message = 'The ' + adjective + noun + ' is' + verb; alert("The story will now be displayed."); document.write(message);

Please help me with this string formatting issue. Thank you.

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

You could do it like this:

var message = 'The ' + adjective + ' ' + noun + ' is ' + verb;

Try that out and see if it looks better :smile:

I tried out your code and the printed output was better. Thank you.