如何在 JavaScript 中将字符串转换为脊柱案例? [英] How do I convert a string to spinal case in JavasScript?
问题描述
我被freeCodeCamp的这个编码挑战Spinal Tap Case困住了.基本上我不知道如何让最后一个检查执行.
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.
这是最后一次检查:spinalCase("AllThe-small Things") 应该返回"all-the-small-things"
这是我的代码:
function spinalCase(str) {
var outputString,
newstr,
pattern1 = new RegExp(/[_\s]/, 'g'),
pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
stringTest1 = pattern1.test(str),
stringTest2 = pattern2.test(str);
if(stringTest1) {
outputString = str.replace(pattern1, '-');
newstr = outputString.toLowerCase();
} else if(stringTest2) {
str.split(/(?=[A-Z])/).join(' ');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
} else if (stringTest1 && stringTest2){
outputString = str.replace(pattern1, '-');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
}
return newstr;
}
我确实意识到最后一个 else if
条件应该先行,但是我没有得到正确的语法.
I do realize the last else if
condition should go first however I didn't get the syntax right.
提前致谢!
推荐答案
我建议这样做:
function sp(str) {
var spinal = str.replace(/(?!^)([A-Z])/g, ' $1')
.replace(/[_\s]+(?=[a-zA-Z])/g, '-').toLowerCase();
return spinal
}
就您的代码而言,您检查:
as far as your code, you check for:
if test1
else if test2
, then else if test1 and test2
,逻辑不对:
if test1
else if test2
, then else if test1 and test2
, the logic is not correct:
您可以尝试将 !test2
或 !test1
添加到第一个 if 检查以使其正常工作:
you could try to adding a !test2
or !test1
to the first if checks to get it working:
if (stringTest1 && !stringTest2)...
这里是你如何让你的代码在最后一个 else if 中触发,我在那里放了一个 console.log 来向你展示:
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:
function spinalCase(str) {
var outputString,
newstr,
pattern1 = new RegExp(/[_\s]/, 'g'),
pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
stringTest1 = pattern1.test(str),
stringTest2 = pattern2.test(str);
if(stringTest1 && !stringTest2) {
outputString = str.replace(pattern1, '-');
newstr = outputString.toLowerCase();
} else if(!stringTest1 && stringTest1) {
str.split(/(?=[A-Z])/).join(' ');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
} else if (stringTest1 && stringTest2){
console.log('were in the last else!!!');
outputString = str.replace(pattern1, '-');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
}
return newstr;
}
这篇关于如何在 JavaScript 中将字符串转换为脊柱案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!