Skip to content

Instantly share code, notes, and snippets.

@youssman
Created November 5, 2014 11:19
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save youssman/745578062609e8acac9f to your computer and use it in GitHub Desktop.
Save youssman/745578062609e8acac9f to your computer and use it in GitHub Desktop.
Javascript convert camelcase to dash (hyphen)
function camelCaseToDash( myStr ) {
return myStr.replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
}
var myStr = camelCaseToDash( 'thisString' );
alert( myStr ); // => this-string
@canvaspixels
Copy link

This doesn't cover single chars e.g. thisIsAString.

This will :)

return myStr.replace(/([A-Z])/g, (g) => -${g[0].toLowerCase()});

@luckylooke
Copy link

@canvaspixels Unexpected token {

@cmoesel
Copy link

cmoesel commented Feb 18, 2017

@luckylooke -- I think @canvaspixels' example was corrupted by the markdown rendering. I expect he meant this:

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

@jamespsterling
Copy link

Great help. thanks

@javiersuazomatus
Copy link

javiersuazomatus commented Jul 25, 2017

For javascript I recommend this way:

return !myStr ? null : myStr.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase() });

@roziscoding
Copy link

I tried the solutions proposed here, but they didn't work for strings that start with an upper case letter.
Here's my improved version:

const camelToDash = str => str
    .replace(/(^[A-Z])/, ([first]) => first.toLowerCase())
    .replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`)

@anik
Copy link

anik commented Dec 22, 2017

_.kebabCase( 'fontSize' )
// font-size

@imkost
Copy link

imkost commented Dec 26, 2017

/**
 * camelCaseToDash('userId') => "user-id"
 * camelCaseToDash('waitAMoment') => "wait-a-moment"
 * camelCaseToDash('TurboPascal') => "turbo-pascal"
 */
function camelCaseToDash (str) {
  return str.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase()
}

@shaddyz
Copy link

shaddyz commented May 12, 2018

This version will handle imperfect camel case/pascal case with multiple capital letters in a row

function camelCaseToDash(str) {
    return str
        .replace(/[^a-zA-Z0-9]+/g, '-')
        .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
        .replace(/([a-z])([A-Z])/g, '$1-$2')
        .replace(/([0-9])([^0-9])/g, '$1-$2')
        .replace(/([^0-9])([0-9])/g, '$1-$2')
        .replace(/-+/g, '-')
        .toLowerCase();
}

@ORESoftware
Copy link

ORESoftware commented Sep 6, 2018

this might be simpler:

const camel2Dash = (v: string): string => {
  
  let ret = '', prevLowercase = false;
  
  for(let s of v){
    
    const isUppercase = s.toUpperCase() === s;
    if(isUppercase && prevLowercase){
      ret += '-';
    }
    
    ret += s;
    prevLowercase = !isUppercase;
  }
  
  return ret.replace(/-+/g, '-').toLowerCase();
  
};

it just checks to see if the previous was lowercase and current is uppercase, and in that case adds a hyphen. at the end replaces more than one consecutive hyphen with just one hyphen.

For emdash/endash, will have to do more.

@ferni
Copy link

ferni commented Jul 3, 2019

I tried the solutions proposed here, but they didn't work for strings that start with an upper case letter.

That's not camel case.

@maddb3457
Copy link

I tried the solutions proposed here, but they didn't work for strings that start with an upper case letter.

That's not camel case.

That is PascalCase

@21tretiak0101
Copy link

str.split(/(?=[A-Z])/).join('-').toLowerCase()

@stepanmas
Copy link

str.split(/(?=[A-Z])/).join('-').toLowerCase()

'propName1'.split(/(?=[A-Z])/).join('-').toLowerCase() -> "prop-name1"

@dohomi
Copy link

dohomi commented Oct 16, 2020

I extended https://gist.github.com/youssman/745578062609e8acac9f#gistcomment-2698925 with numbers:

const camelCaseToDash = (v) => {
  let ret = '', prevLowercase = false, prevIsNumber = false
  for (let s of v) {
    const isUppercase = s.toUpperCase() === s
    const isNumber = !isNaN(s)
    if (isNumber) {
      if (prevLowercase) {
        ret += '-'
      }
    } else {
      if (isUppercase && (prevLowercase || prevIsNumber)) {
        ret += '-'
      }
    }
    ret += s
    prevLowercase = !isUppercase
    prevIsNumber = isNumber
  }
  return ret.replace(/-+/g, '-').toLowerCase()
}
// mdiDiceD10Outline =>  mdi-dice-d10-outline
// mdiKeyboardF10 mdi-keyboard-f10
// mdiNumeric1 mdi-numeric-1

@xgqfrms
Copy link

xgqfrms commented Feb 4, 2021

"use strict";

/**
 * 
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2021-02-04
 * 
 * @description camelCaseFormatter 驼峰命名转换器
 * @augments 
 * @example 
 * @link https://www.cnblogs.com/xgqfrms/p/14366997.html
 * @link https://vscode.xgqfrms.xyz/
 * 
 */

const log = console.log;


const camelCaseFormatter = (str = ``, debug = false) => {
    let result = '';
    for(let item of [...str]) {
        if(item.charCodeAt() > 'a'.charCodeAt() || !Number.isNaN(+item)) {
            result += item;
        } else {
            result += `-${item.toLocaleLowerCase()}`;
        }
    }
    if(debug) {
        log(`✅ result = `, result);
    }
    return result;
}

const str = 'costInV2';
// "costInV2"

camelCaseFormatter(str, true);


// node  ./camelCase.js
// result =  cost-in-v2

@bilogic
Copy link

bilogic commented May 5, 2024

is there one that deals with paths? /CamelCase/Path/Here to /camel-case/path/here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment