Skip to content

Instantly share code, notes, and snippets.

@ZachWatkins
Created April 16, 2024 03:28
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 ZachWatkins/42076179ab3feddaf75da1f1eb20a61c to your computer and use it in GitHub Desktop.
Save ZachWatkins/42076179ab3feddaf75da1f1eb20a61c to your computer and use it in GitHub Desktop.
Convert text to scripting cases
/**
* Change case of text to common programming language cases.
* @param {string} text - Text to change case. May contain spaces, special characters, etc.
* @param {string} caseType - Type of case to change to. Possible values are:
* - camelCase
* - PascalCase
* - snake_case
* - kebab-case
* - CONSTANT_CASE
* - TitleCase
* @returns {string} - Text with case changed to the specified case type.
*/
function changeCase(text, caseType) {
if (caseType === 'camelCase') {
return text
.replace(/\s(.)/g, ($1) => $1.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, ($1) => $1.toLowerCase());
} else if (caseType === 'PascalCase') {
return text
.replace(/\s(.)/g, ($1) => $1.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, ($1) => $1.toUpperCase());
} else if (caseType === 'snake_case') {
return text
.replace(/\s/g, '_')
.replace(/([A-Z])/g, ($1) => '_' + $1.toLowerCase())
.replace(/^_/, '');
} else if (caseType === 'kebab-case') {
return text
.replace(/\s/g, '-')
.replace(/([A-Z])/g, ($1) => '-' + $1.toLowerCase())
.replace(/^-/, '');
} else if (caseType === 'CONSTANT_CASE') {
return text
.replace(/\s/g, '_')
.replace(/([A-Z])/g, ($1) => '_' + $1)
.replace(/^_/, '')
.toUpperCase();
} else if (caseType === 'TitleCase') {
return text
.replace(/\b\w/g, ($1) => $1.toUpperCase())
.replace(/\s/g, '');
} else {
return text;
}
}
const sampleText = 'This is a sample text';
function it(description, test) {
console.log(description + ' - ' + (test() ? 'PASSED' : 'FAILED'));
}
it('camelCase', () => changeCase(sampleText, 'camelCase') === 'thisIsASampleText');
it('PascalCase', () => changeCase(sampleText, 'PascalCase') === 'ThisIsASampleText');
it('snake_case', () => changeCase(sampleText, 'snake_case') === 'this_is_a_sample_text');
it('kebab-case', () => changeCase(sampleText, 'kebab-case') === 'this-is-a-sample-text');
it('CONSTANT_CASE', () => changeCase(sampleText, 'CONSTANT_CASE') === 'THIS_IS_A_SAMPLE_TEXT');
it('TitleCase', () => changeCase(sampleText, 'TitleCase') === 'ThisIsASampleText');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment