I am generating some meaningful name with the following rule in a JavaScript/Node JS program:
Input: “tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId“
Expected output: “TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId”
Rules:
- replace any character with zero or more underscore to the non-underscored uppercase
Example:x | __*x => X
- If exists remove last _
This is what is tried so far, looking for better alternatives, if any:
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;
}
}