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

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

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?

Thanks

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()]