Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-doherty/185254378496af4ea35c21e8e3f6e3a8 to your computer and use it in GitHub Desktop.
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
/**
* 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