[英]Convert sentence or camelCase word to spinal-case
I am trying to convert both sentence case and camel case to spinal case. 我试图将判决案件和骆驼案件转换为脊柱病例。
I am able to change camel case to by adding a space before every capital letter, but when I apply it to sentences with capital letters after spaces, I get extra spacing. 我能够通过在每个大写字母之前添加一个空格来改变驼峰的情况,但是当我将它应用于空格后的大写字母的句子时,我得到额外的间距。
Here is my function so far : 到目前为止,这是我的功能:
function spinalCase(str) {
var noCamel = str.replace(/([A-Z])/g, ' $1');
var newStr = noCamel.replace(/\s|_/g, "-");
return newStr.toLowerCase();
}
spinalCase("makeThisSpinal"); //returns make-this-spinal
spinalCase("Make This Spinal"); //returns -make--this--spinal
Get lodash, specifically, https://lodash.com/docs#kebabCase . 获取lodash,具体来说, 请访问https://lodash.com/docs#kebabCase 。
_.kebabCase('makeThisSpinal') // make-this-spinal
_.kebabCase('Even Sentences Work') // even-sentences-work
Instead of: 代替:
var noCamel = str.replace(/([A-Z])/g, ' $1');
Try: 尝试:
var noCamel = str.replace(/(\B[A-Z])/g, ' $1');
It's because you're replacing all capital letters with a space and its lowercase letter. 这是因为你用空格和小写字母替换所有大写字母。 So in your sentence, you're getting two spaces before
this
and spinal
. 所以在你的句子中,你在
this
之前得到两个空格并且spinal
。
What you can do is replace all uppercase letters with "-$1"
and then just remove all spaces from the string. 你可以做的是用
"-$1"
替换所有大写字母,然后从字符串中删除所有空格。
function spinalCase(str) {
var noCamel = str.replace(/([a-z](?=[A-Z]))/g, '$1 ')
var newStr = noCamel.replace(/\s|_/g, "-");
return newStr.toLowerCase();
}
spinalCase("makeThisSpinal"); //returns make-this-spinal
spinalCase("Make This Spinal"); //returns -make-this-spinal
Instead of str.replace(/([AZ])/g, ' $1')
for the camel case split, you should use str.replace(/([az](?=[AZ]))/g, '$1 ')
which will space out each word regardless of case. 对于驼峰案例拆分而不是
str.replace(/([AZ])/g, ' $1')
,你应该使用str.replace(/([az](?=[AZ]))/g, '$1 ')
无论如何都会将每个单词分开。
Here's my solution, perhaps you will find it good reference: 这是我的解决方案,也许你会发现它很好的参考:
function spinalCase(str) {
var newStr = str[0];
for (var j = 1; j < str.length; j++) {
// if not a letter make a dash
if (str[j].search(/\W/) !== -1 || str[j] === "_") {
newStr += "-";
}
// if a Capital letter is found
else if (str[j] === str[j].toUpperCase()) {
// and preceded by a letter or '_'
if (str[j-1].search(/\w/) !== -1 && str[j-1] !== "_") {
// insert '-' and carry on
newStr += "-";
newStr += str[j];
}
else {
newStr += str[j];
}
}
else {
newStr += str[j];
}
}
newStr = newStr.toLowerCase();
return newStr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.