Regex to split camel case
My guess is replacing /([A-Z])/
with /([a-z])([A-Z])/
and ' $1'
with '$1 $2'
"MyCamelCaseString"
.replace(/([a-z])([A-Z])/g, '$1 $2');
/([a-z0-9])([A-Z])/
for numbers counting as lowercase characters
console.log("MyCamelCaseStringID".replace(/([a-z0-9])([A-Z])/g, '$1 $2'))
If you want an array of lower case words:
"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase());
If you want a string of lower case words:
"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase()).join(' ');
If you want to separate the words but keep the casing:
"myCamelCaseString".replace(/([a-z])([A-Z])/g, '$1 $2')
"MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')
outputs:
"My Camel Case String"
Sometime camelCase strings include abbreviations, for example:
PDFSplitAndMergeSamples
PDFExtractorSDKSamples
PDFRendererSDKSamples
BarcodeReaderSDKSamples
And in this case the following function will work, it splits the string leaving abbreviations as separate strings:
function SplitCamelCaseWithAbbreviations(s){
return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
}
Example:
function SplitCamelCaseWithAbbreviations(s){
return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
}
console.log(SplitCamelCaseWithAbbreviations('PDFSplitAndMergeSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFExtractorSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFRendererSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('BarcodeReaderSDKSamples'));