Spinal Tap Case
function spinalCase(str) {
return str.replace(/[A-Z]/g, ` $&`)//大写左侧加空格(针对骆驼式字符串)
.replace(/_/g, ` `)//下划线变空格(下划线间隔的字符串)
.toLowerCase()//
.split(/\\W/)//非字母字符为基准分割为数组
.filter(str=> str.trim()!="")//去空格,过滤非有效元素
.join("-")
}
spinalCase('This Is Spinal Tap');
转换结果示例:
"This Is Spinal Tap" -> "this-is-spinal-tap" "thisIsSpinalTap" -> "this-is-spinal-tap" "The_Andy_Griffith_Show" -> "the-andy-griffith-show" "Teletubbies say Eh-oh" -> "teletubbies-say-eh-oh" "AllThe-small Things" -> "all-the-small-things".
//别人家的孩子
function spinalCase(str) {
// Create a variable for the white space and underscores.
var regex = /\\s+|_+/g;//空白字符 和 下划线(空白字符包括短横杠)
// Replace low-upper case to low-space-uppercase
str = str.replace(/([a-z])([A-Z])/g, "$1 $2");//大、小写字母间加空格
// Replace space and underscore with -
return str.replace(regex, "-").toLowerCase();//原本就有短横杠的,不变
}
spinalCase("This Is Spinal Tap");
function spinalCase(str) {
// Replace low-upper case to low-space-uppercase
str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
// Split on whitespace and underscores and join with dash
return str
.toLowerCase()
.split(/(?:_| )+/)//带() 会多匹配出元素,用?: 消除这个效果
.join("-");
}
spinalCase("This Is Spinal Tap");
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str
.split(/\\s|_|(?=[A-Z])/)//空格、下划线、
.join("-")
.toLowerCase();
}
//x(?=y) 当'x'后面跟着'y'时匹配'x'
// x 可以是"" 空字符
//(?=y) y前面的位置
//.split(/(?=[A-Z])/) 在大写字母前面的位置分割
//Σ(っ °Д °;)っ
//o((⊙﹏⊙))o.
//b( ̄▽ ̄)d