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 Vue.js Basics Sweeping Vues: Loops, Methods, Directives Conditionally Adding or Removing Classes

How can you add a "-" in between class names that are separated by a space?

I have this solution for challenge she gave in the last video

        <li v-show="type === '' || type === media.type" 
            v-for="media in mediaList" 
            v-bind:class="[media.showDetail ? 'less': 'more', media.type.replace(' ', '-').toLowerCase()]">
          <div v-show="media.showDetail">
            <p v-if="media.contributor" class="byline">By: {{media.contributor}}</p>

This works. However, only for the very first space in a string of words. For example:

'str one' => 'str-one'

'str one str two' => 'str-one str two'

Only the first encountered space gets a hyphen... why?


3 Answers

Mike's answer is the most expressive, since RegEx can be difficult to read for the unfamiliar.

However, to piggyback on Kris' answer, I'd use the RegEx whitespace character:

// \s - matches all whitespace
// g - doesn't stop after the first match
media.type.replace(/\s/g, '-').toLowerCase();

According to this page : If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier.

For example

string.replace(/str /g, "str-");

would replace all instances of str{space} with str-

I use split, which works well

[media.showDetail ? 'less': 'more', media.type.split(' ').join('-').toLowerCase()]