How to convert a camel-case string to dashes in JavaScript?

前端 未结 7 1275
情深已故
情深已故 2021-02-13 02:22

I want to convert these strings:

fooBar
FooBar

into:

foo-bar
-foo-bar

How would I do this in JavaScript the m

相关标签:
7条回答
  • 2021-02-13 03:10

    EDIT

    Simple case:

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

    Edge case: this can get an extreme case where you have a single char.

    "FooBarAFooBar".replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)
    
    0 讨论(0)
  • 2021-02-13 03:14

    For those who do not need the preceding hyphen:

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

    0 讨论(0)
  • 2021-02-13 03:15

    You can use replace with a regex like:

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

    which matches all uppercased letters and replace them with their lowercased versions preceded by "-".

    Example:

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

    0 讨论(0)
  • 2021-02-13 03:20

    You can use

    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`))
    
    0 讨论(0)
  • 2021-02-13 03:21

    You can use replace() with regex. Then use toLowerCase()

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

    `

    0 讨论(0)
  • 2021-02-13 03:23

    You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.

    0 讨论(0)
提交回复
热议问题