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


Can someone explain the logic of "replace(/\w\S*" to me?

Hi all,

I'm doing some JavaScript exercises and i can't seem to wrap my head around this one. The assignment is to "Write a JavaScript function to capitalize the first letter of each word in a string". So far it's pretty clear and i can work my way towards it but the answer provides this piece of code:

function capitalize_Words(str)  
 return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});  

I understand the code but i just cannot seem to wrap my head around the /\w\S* part in the replace method. I know a /s "select" whitespace and /g selects each instance but what's the use of "/\w"? And why the \S with a capital and an "*" after it.

If someone could explain this to me....


1 Answer

Josip Dorvak
Josip Dorvak
18,126 Points

The / Is the beginning of a regex (regular expression). The \w looks for all word characters in a string. A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character. Now the \S is any character that is NOT a whitespace character. You were confusing it with \s(lowercase) which is for whitespace characters. The * is a character that says to look for n zero or more times, where n is the metacharacter(the backslash tokens in the regex) in the regex. Hope this helped a little.

If you need more help go to: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Exactly what i was looking for. This explains everything i wanted to know!

Thanks :)