【问题标题】:How to convert a camel-case string to dashes in JavaScript?如何在 JavaScript 中将驼峰式字符串转换为破折号?
【发布时间】:2018-05-29 21:39:57
【问题描述】:

我想转换这些字符串:

fooBar
FooBar

进入:

foo-bar
-foo-bar

对于任何给定的字符串,我如何在 JavaScript 中以最优雅和最高效的方式执行此操作?

【问题讨论】:

  • 拆分成一个字符数组,检查大写字符,将它们替换为小写字母+前面的破折号,将数组组合回一个字符串。
  • @Danmoreng 正则表达式不是更好吗?
  • 当然你也可以使用带有String.replace的正则表达式
  • 我猜是最优雅的——很可能不是最高效的解决方案

标签: javascript string camelcasing


【解决方案1】:

您可以将replace 与如下正则表达式一起使用:

let dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());

匹配所有大写字母并将它们替换为以"-"开头的小写版本。

示例:

console.log("fooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));

【讨论】:

    【解决方案2】:

    也许你可以使用来自 lodash 的 kebabCasehttps://lodash.com/docs/4.17.15#kebabCase

    【讨论】:

      【解决方案3】:

      对于那些不需要前面连字符的人:

      console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))

      【讨论】:

        【解决方案4】:

        您可以将replace() 与正则表达式一起使用。然后使用toLowerCase()

        let camel = (s) => s.replace(/[A-Z]/g, '-$&').toLowerCase()
        
        console.log(camel('fooBar'))
        console.log(camel('FooBar'))

        `

        【讨论】:

        • 请注意:您不需要对比赛进行分组。只需删除括号并使用$&
        • @ibrahimmahrir 很好但是documentation有警告通知
        【解决方案5】:

        您可以使用 underscore.string 库中的https://github.com/epeli/underscore.string#dasherizestring--string

        【讨论】:

        • 我喜欢“不要重新发明轮子的方法”
        【解决方案6】:

        你可以使用

        const makeItDashed = camelCased => {
           let dashed = ``
           camelCased.split(``).map(ch => {{dashed += ch.toUpperCase() == ch ? `-${ch.toLowerCase()}` : ch}})
           return dashed
        }
        
        console.log(makeItDashed(`fooBar`))
        console.log(makeItDashed(`FooBar`))
        

        【讨论】:

          【解决方案7】:

          编辑

          简单案例:

          "fooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();   
          "FooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
          

          边缘情况:这可能会导致您只有一个字符的极端情况。

          "FooBarAFooBar".replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)
          

          【讨论】:

          • OP 也想包含第一个字母。
          • 嗨@ibrahimmahrir 感谢让我注意到,这应该解决他的问题,并考虑他有一个大写字母字符的边缘情况。 "FooBarAFooBar".replace(/([A-Z])/g, (g) => -${g[0].toLowerCase()})
          • 不必要的复杂正则表达式模式,这就是你需要单独处理单个大写的原因
          猜你喜欢
          • 2012-05-12
          • 2015-07-07
          • 1970-01-01
          • 2012-01-20
          • 1970-01-01
          • 2011-02-27
          • 2011-10-03
          相关资源
          最近更新 更多