简体   繁体   English

当字符串中的单词不由空格分隔时,隐式字符串到脊柱的情况

[英]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: 过程是这样的:

  1. First letter doesn't change anything, so let it out. 第一个字母不会改变任何内容,因此请使其消失。
  2. In the rest of your string, you have two conditions: 在字符串的其余部分,您有两个条件:

    • You just have a space or an underscore, then you should replace it with a dash. 您只有一个空格或下划线,然后应将其替换为破折号。
    • You have a capital letter, then you should replace it with a dash followed by that letter. 您有一个大写字母,然后应该用破折号代替该字母。

    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")调用,可以解决一个替换的两个条件。

    • If the regex matches a space or underscore, it'll replace it by just a dash ( $2 will match nothing, because it doesn't match a capital letter). 如果正则表达式匹配空格或下划线,则将其替换为短划线( $2将不匹配,因为它不匹配大写字母)。
    • If the regex matches a capital letter, it'll replace it by a dash followed by that letter ( $2 will be have the value of that letter). 如果正则表达式与大写字母匹配,则将其替换为破折号,后跟该大写字母( $2将具有该大写字母的值)。
  3. We concatenate the first letter with the rest (after replacing). 我们将第一个字母与其余字母连接起来(替换后)。
  4. We lower-case the result. 我们将结果小写。
  5. Done! 做完了!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM