Truncate a String - Using RegExp and failing one test

Truncate a String - Using RegExp and failing one test
0.0 0

#1

Hey guys - I’m not 100% why I’m not passing this challenge. The only test I am failing is the “tisket tasket blah blah” one. From what I can tell, it should pass based on what the challenge is asking for. I was hoping to make this work without the extra if statement, but I was returning a null in addition to the string when the num passed in was greater than the strength’s length. Any ideas/thoughts?

I haven’t thought of other ways to do this one yet, but I’m imagining something along the lines of converting the string to an array, and splicing it based on the num passed in possibly. I think there’s a couple of ways it can probably be done if I go the array route.

Are my thought processes/ideas in line with what they should be? Some of these challenges make me question my life choices for a while lol.

Your code so far


function truncateString(str, num) {
  // Clear out that junk in your trunk
  
  let regex = RegExp("^" +"." + "{" + num + "}", "gi");
  if (num > str.length) {
    let diff = num - str.length;
    regex = RegExp("^" +"." + "{" + (num - diff) + "}", "gi");
    console.log(str.match(regex));
    return str.match(regex);
  }
  return str.match(regex) + "...";
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string


#2

Unless you love pain, my suggestion is to stay away from regex if there’s another way. So just use an array. They’re cheap to create and iterate over. Occam’s razor – simplest solution wins. And regex is hardly ever simple. lol