Skip to content

Instantly share code, notes, and snippets.

@youssman
Created November 5, 2014 11:19
Show Gist options
  • 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
@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