Created
June 16, 2019 18:12
-
-
Save john-doherty/185254378496af4ea35c21e8e3f6e3a8 to your computer and use it in GitHub Desktop.
Converts a string to JSON safe key (property name) by removing unsafe characters and converting to camel case
This file contains 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
/** | |
* Converts a string to JSON safe key (property name) by removing unsafe | |
* characters and converting to camel case | |
* @param {string} src - string to convert | |
* @Example | |
* stringToJsonSafeKey('r@ndAm wo5d') // rndamWo5d | |
* @returns {string} id/key safe string | |
*/ | |
function stringToJsonSafeKey(src) { | |
// remove unsafe characters | |
src = (src || '').replace(/[^a-zA-Z0-9-_ ]/g, '').trim(); | |
// camel case if it contains multiple words, or just lowercase | |
return src.split(' ').map(function(word, index) { | |
// if it's the first word, lowercase | |
if (index === 0) { | |
return word.toLowerCase(); | |
} | |
// otherwise upper case the first char and lowercase the rest | |
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); | |
}).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment