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

Regex delimiters put back into use?

I am a bit stuck on this, can't figure out how to re-insert the non-word characters ie. "-" and "!". I used regex as a way to split based on those delimiters but do need to retain the indices of the "-" and the "!" and re-introduce once I convert it back into a string from the array. The desired output is "e6t-r3s are r4y fun!" and so far I am getting: 'e6t r3s are r4y fun '

Write a function that takes a string and turns any and all "words" (see below) within that string of length 4 or greater into an abbreviation following the same rules.

abbreviate("elephant-rides are really fun!");

function abbreviate(string) {
    var array = string.split(/\W/); 
    var newArray = [];
    for (var i = 0; i < array.length; i++) {//iterates through each word
      var word = array[i];
      var abbrString = "";
      if (word.length >= 4) {
          //concat first index,count of indexes in between, last index
          var innerChar = word.substring(1, word.length - 1);
          var indCount = innerChar.length;
          var abbrWord = word.charAt(0) + indCount + word.charAt(word.length-1); 
          newArray.push(abbrWord);
        } else {
          newArray.push(word);
        }

    }
  return newArray.join(" ");
}

Moderator edited: Added markdown so the code renders properly in the forums.

can you specify what are the rules?

1 Answer

instead of splitting on non-word with W, you could split on spaces with s. this would retain the exclamation point at the end. the first element would be elephant-rides, which you could split again on the dash, then join back together on a dash, before joining with the other words on a space to get the desired result.