I am stuck on this coding challenge Spinal Tap Case from freeCodeCamp. Essentially I don’t know how to get the last check to execute.
This is the last check:
spinalCase("AllThe-small Things") should return "all-the-small-things"
And this is my code:
JavaScript
x
25
25
1
function spinalCase(str) {
2
var outputString,
3
newstr,
4
pattern1 = new RegExp(/[_s]/, 'g'),
5
pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
6
stringTest1 = pattern1.test(str),
7
stringTest2 = pattern2.test(str);
8
9
if(stringTest1) {
10
outputString = str.replace(pattern1, '-');
11
newstr = outputString.toLowerCase();
12
} else if(stringTest2) {
13
str.split(/(?=[A-Z])/).join(' ');
14
outputString = str.replace(pattern2, '-');
15
newstr = outputString.toLowerCase();
16
} else if (stringTest1 && stringTest2){
17
outputString = str.replace(pattern1, '-');
18
outputString = str.replace(pattern2, '-');
19
newstr = outputString.toLowerCase();
20
}
21
22
return newstr;
23
24
}
25
I do realize the last else if
condition should go first however I didn’t get the syntax right.
Thanks in advance!
Advertisement
Answer
Here is how I recommend doing it:
JavaScript
1
6
1
function sp(str) {
2
var spinal = str.replace(/(?!^)([A-Z])/g, ' $1')
3
.replace(/[_s]+(?=[a-zA-Z])/g, '-').toLowerCase();
4
return spinal
5
}
6
as far as your code, you check for:
if test1
else if test2
, then else if test1 and test2
, the logic is not correct:
you could try to adding a !test2
or !test1
to the first if checks to get it working:
JavaScript
1
2
1
if (stringTest1 && !stringTest2)
2
EDIT:
here is how you can get your code to fire in that last else if, I put a console.log in there to show you here:
JavaScript
1
26
26
1
function spinalCase(str) {
2
var outputString,
3
newstr,
4
pattern1 = new RegExp(/[_s]/, 'g'),
5
pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
6
stringTest1 = pattern1.test(str),
7
stringTest2 = pattern2.test(str);
8
9
if(stringTest1 && !stringTest2) {
10
outputString = str.replace(pattern1, '-');
11
newstr = outputString.toLowerCase();
12
} else if(!stringTest1 && stringTest1) {
13
str.split(/(?=[A-Z])/).join(' ');
14
outputString = str.replace(pattern2, '-');
15
newstr = outputString.toLowerCase();
16
} else if (stringTest1 && stringTest2){
17
console.log('were in the last else!!!');
18
outputString = str.replace(pattern1, '-');
19
outputString = str.replace(pattern2, '-');
20
newstr = outputString.toLowerCase();
21
}
22
23
return newstr;
24
25
}
26