I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):
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')
Hi I saw no live demo , thanks @michiel-dral
var tests =[ "camelCase",
"simple",
"number1Case2"]
function getCamelCaseArray(camel) {
var reg = /([a-z0-9])([A-Z])/g;
return camel.replace(reg, '$1 $2').split(' ');
}
function printTest(test) {
document.write('<p>'+test + '=' + getCamelCaseArray(test)+'</p>');
}
tests.forEach(printTest);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
</body>
</html>
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'));
a = 'threeBlindMice'
a.match(/[A-Z]?[a-z]+/g) // [ 'three', 'Blind', 'Mice' ]
is the simplest way I've found, for simple camel/titlecase splitting.
This RegExp String is
.replace("/([a-zA-Z][a-z]*)/g",...);
"MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')
outputs:
"My Camel Case String"