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 trialmattcleary2
19,953 PointsCan somebody please explain how username works?
Hey guys,
Can somebody please explain what this means?
var username = request.url.replace("/", "");?
Why would you set username to nothing?
Immediately following this is:
if(username.length > 0) {
How could username possibly be longer than 0 if it's just been set to an empty string?
Thank you!
3 Answers
andren
28,558 PointsThe replace function looks through a string for the value you define in the first argument and replaces it with the value you define in the second argument.
In other words the code is essentially saying "Replace all instances of / with nothing" it isn't saying replace the string itself with nothing.
If the string in question was "hello /world/!" for example the above code would result in a string that said "hello world!".
Jeremy Castanza
12,081 PointsThe other part to what @andren said has to do with the root. This is also an attempt to isolate the home root route from the user route. By stripping the URL of the "/", there's a distinction between the home (or root) and the user URIs.
mattcleary2
19,953 PointsThank you so much!
James Barrett
13,253 PointsThanks for the comment andren . Quick question, why exactly are we replacing all instances of the "/" with nothing? Thanks, James.
andren
28,558 PointsIt's worth nothing that it's been a while since I completed the Node course, but from skimming though the video I think I more or less understand why.
In the video Andrew is setting up the site so that when you visit a URL that contains a username (/chalkers for example) then the website will respond with a page that simply contains a header, footer and the username that was inserted in the URL.
In order to get the username that was entered he is using "request.url" which will contain the requested URL ("/chalkers" if that is the requested part of the site) and then he strips of the "/" in order to get the pure username and stores that new string "chalkers" as a variable called username, that he can then later use when he is sending out the text that the server responds with.
This means that no matter what name you enter when you visit the website (/andren for example) you will get that name sent back in the response. if he did not strip off the / then the username would include the "/" like this "/andren".