Created
May 29, 2017 11:56
-
-
Save AhsanAyaz/da907e42d982a886a278d1156c2e9cfc to your computer and use it in GitHub Desktop.
A simple Javascript snippet to convert any camelCase or PascalCase string to underscore (or custom joiners)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var testStrSimple = "MyNameIsAhsanAyaz"; | |
var testStrWhiteSpace = "myName \nIsAhsan"; | |
console.log(ccpc2und(testStrSimple)); | |
console.log(ccpc2und(testStrWhiteSpace)); | |
console.log(ccpc2und(testStrWhiteSpace, "__:D__")); // custum joiner | |
// using LONG METHOD (for no reason) | |
console.log(_ccpc2und(testStrSimple)); | |
console.log(_ccpc2und(testStrWhiteSpace)); | |
console.log(_ccpc2und(testStrWhiteSpace, "__:LONG:__")); // custum joiner | |
/** | |
* @author Ahsan Ayaz | |
* Removes whitespace, converts camelCase or PascalCase to underscore (or custom joiner) | |
* @param str {String} . Source string to process upon. Default '' | |
* @param charToJoin {String} . Character to join converting to lower case and joining. Default '_' | |
* @return {String}. Processed string | |
**/ | |
function ccpc2und(str = '', charToJoin = '_'){ | |
return str.replace(/\s/g,'').replace(/(?:^)?([A-Z])/g, (match) => { | |
return `${charToJoin}${match.toLowerCase()}` | |
}).replace(new RegExp(`^${charToJoin}`), ""); | |
} | |
/** | |
* @author Ahsan Ayaz | |
* Removes whitespace, converts camelCase or PascalCase to underscore (or custom joiner) | |
* @param str {String} . Source string to process upon. Default '' | |
* @param charToJoin {String} . Character to join converting to lower case and joining. Default '_' | |
* @return {String}. Processed string | |
**/ | |
function _ccpc2und(str = '', charToJoin = '_'){ // LONG METHOD (for no reason) | |
var modArr = str.replace(/\s/g,'') | |
.replace(/^([a-zA-z])?/, char => char.toLowerCase()) // turn first char lowercase | |
.split(/([a-z][A-Z])/g); //replace whitespace and splits | |
return modArr.map((el)=>{ | |
return (modArr.indexOf(el) %2 !== 1) ? el : (()=>{ | |
let elChars = el.split(''); | |
return `${elChars[0]}${charToJoin}${elChars[1].toLowerCase()}`; | |
})(); | |
}).join(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment