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
@mcaubrey’s suggestion is great. If you want to continue with your current logic with a small modification, you could do:
function addHyphen(str) {
let currentWordIndex = 0; // keeps track of start of each word before next hyphen
let hypenatedStr = ""; // used to build final string
for (let i = 1; i < str.length; i++) {
if (str[i] == str[i].toUpperCase()) {
hypenatedStr += str.slice(currentWordIndex, i) + "-"
currentWordIndex = i;
}
}
return hypenatedStr + str.slice(currentWordIndex); // concatenates the last word
}
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;
}
@mcaubrey Sure, that is nice. I would remove the extra i++;
and just have:
str = str.slice(0,i) + "-" +str.slice(i++);