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 JavaScript Basics Working with Strings Combine Strings

How to trim a user's input?

I'm sure this will be covered later, but it came to mind now. In this video, we see the necessity of adding a space in a concatenated string to make our final message legible. However, what about if a user erroneously adds a space at the end of their name, for example? Is there a trim function (er, command... method?) we can apply to our prompt() method to account for that?

1 Answer

Steven Parker
Steven Parker
230,230 Points

Strings do in fact have a method named "trim" that will remove extra spaces from both the beginning and end.
For example:

let sloppy = "  sample   ";
let neaten = sloppy.trim();    // will be "sample" (no spaces)

So how would I apply this to creating a variable name from a user's input in the prompt() method? Would it go liiiiike...

const name = trim( prompt("What's your name?") );

ooooor

const name = prompt.trim("What's your name?");

oooorrr

const name = prompt("What's your name?");

And then whenever I wanted to ... call? on the name variable, I'd use name.trim() ?

Or maybe do like what you did and have const rawName = prompt("Your name?"); and then create something like const name = rawName.trim(); ?

I suspect I'm getting ahead of myself here, but I must know! lol

Steven Parker
Steven Parker
230,230 Points

"Trim" doesn't take an argument, but "prompt" does, so:

const name = prompt("What's your name?").trim();

Your last example would also work, and would be good if you needed to keep the input intact for some reason.