I have a JavaScript/Node JS program that generates meaningful names according to the following rule:
Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
Expected output: "TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId"
Rules:
- Replace any character with zero or more underscores with the non-underscored uppercase equivalent. Example:
x | __*x => X
- If there is an extra underscore at the end, remove it.
This function has been implemented so far, but I am open to better alternatives:
const convertBetterString = (input) => {
const finalString = [];
if (input && input.includes('_')) {
const inputStringSeparation = input.split('_');
if (inputStringSeparation.length > 1) {
if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
}
inputStringSeparation.forEach((val, index) => {
if (val === '' && inputStringSeparation[index + 1]) {
const actualString = inputStringSeparation[index + 1];
const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
finalString.push(formattedString);
}
});
return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
} else {
return input.charAt(0).toUpperCase() + input.slice(1);
}
} else {
return input;
}
}