[英]covert string to spinal case when words in string are not separated by spaces
spinal case is separating words by dashes. 脊髓的情况是用破折号隔开单词。 i have the following code that works if words are separated by spaces, but not if you have a string where words are NOT separated by spaces like so: "ThisIsSpinalCase", which should return "this-is-spinal-case".
我有以下代码,如果单词之间用空格分隔,则有效,但如果字符串中的单词之间不使用空格分隔,则该代码无效:“ ThisIsSpinalCase”,应返回“ this-is-spinal-case”。 can't think of a way to recognize every new word in a str.
想不出一种方法来识别str中的每个新单词。 suggestions?
建议?
function spinalCase(str) {
return str.replace(/[\s\W_]/g, "-").toLowerCase();
}
spinalCase('This_is spinal case'); // returns this-is-spinal-case
edit: i realize i can probably check for when there is a new uppercase letter but this would require adding a space between the last word and the next word 编辑:我意识到我可能可以检查何时有一个新的大写字母,但这将需要在最后一个单词和下一个单词之间添加一个空格
The process is like this: 过程是这样的:
In the rest of your string, you have two conditions: 在字符串的其余部分,您有两个条件:
However, you can solve these two conditions, with one replace, by using this call of replace replace(/(([AZ])|[\\s_])+/g, "-$2")
, this means that: 但是,通过使用一次replace
replace(/(([AZ])|[\\s_])+/g, "-$2")
调用,可以解决一个替换的两个条件。
$2
will match nothing, because it doesn't match a capital letter). $2
将不匹配,因为它不匹配大写字母)。 $2
will be have the value of that letter). $2
将具有该大写字母的值)。 Example: 例:
function spinalCase(str) {
return (str[0] + str.substr(1).replace(/(([A-Z])|[\s_])+/g, "-$2")).toLowerCase();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.