Can this be done with a for loop?

Objective: for an input string such as “ThisIsAnExample” the function should return “This-Is-An-Example”

I have this so far

function addHyphen(str) {

 for(let i = 1 ; i<str.length ; i++) {
   if (str[i] == str[i].toUpperCase()) {
     var str2 = str.slice(0,i) + "-" +str.slice(i)
   }
 }
  
}

Of course, console logging this gives:

“This-IsAnExample”
“ThisIs-AnExample”
“ThisIsAn-Example”

So while the code does add a ‘-’ before each capital letter after the first, it does not ‘remember’ each one as the value of str2 gets reassigned

Short version: Yes, yes you can.

You don’t need str2. You can assign the changes to your str variable (str = str.slice(0,i) + "-" +str.slice(i)). Since your str variable will get longer when that happens, and since you need to make sure you skip your newly created -, you’ll want to increase your iterator variable (i) by 1 if you add a dash. Then you can just return str.

2 Likes

I feel like this would be a simpler way to appropriate their current code (following what I wrote here).

function addHyphen(str) {
    for(let i = 1 ; i<str.length ; i++) {
        if (str[i] == str[i].toUpperCase()) {
            str = str.slice(0,i) + "-" +str.slice(i); i++;
        }
    }
    return str;
}