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):
Regex not-a word boundary \B
character can also be used
console.log("MyCamelCaseString".replace(/(\B[A-Z])/g, ' $1'));
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'))
I prefer to work with arrays over strings. It's easier to debug and more flexible. This is an actual join
instead of replace
. I haven't dealt with white spaces in the strings but you could just trim each element easily enough.
const splitCamelCase = str => str.match(/^[A-Z]?[^A-Z]*|[A-Z][^A-Z]*/g).join(' ');
console.log(splitCamelCase('fooMyCamelCaseString'));
console.log(splitCamelCase('MyCamelCaseString'));
console.log(splitCamelCase('XYZMyCamelCaseString'));
console.log(splitCamelCase('alllowercase'));
If you want to capitalize and add space between numbers as well, this works.
const str = 'this1IsASampleText';
str.charAt(0).toUpperCase() + value.slice(1); // Capitalize the first letter
str.replace(/([0-9A-Z])/g, ' $&'); // Add space between camel casing
Results:
This 1 Is A Sample Text
You can use a combination of regEx
, replace
, and trim
.
"ABCMyCamelCaseSTR".replace(/([A-Z][a-z0-9]+)/g, ' $1 ')
.replace(/\s{2}/g," ").trim()
// ABC My Camel Case STR
I found that none of the answers for this question really worked in all cases and also not at all for unicode strings, so here's one that does everything, including dash and underscore notation splitting.
let samples = [
"ThereIsWay_too MuchCGIInFilms These-days",
"UnicodeCanBeCAPITALISEDTooYouKnow",
"CAPITALLetters at the StartOfAString_work_too",
"As_they_DoAtTheEND",
"BitteWerfenSie-dieFußballeInDenMüll",
"IchHabeUberGesagtNichtÜber",
"2BeOrNot2Be",
"ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
];
samples.forEach(sample => console.log(sample.replace(/([^[\p{L}\d]+|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}[\p{Ll}\d])|(?<=[\p{L}\d])(?=\p{Lu}[\p{Ll}\d]))/gu, '-').toUpperCase()));
If you don't want numbers treated as lower case letters, then:
let samples = [
"2beOrNot2Be",
"ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
];
samples.forEach(sample => console.log(sample.replace(/([^\p{L}\d]+|(?<=\p{L})(?=\d)|(?<=\d)(?=\p{L})|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}\p{Ll})|(?<=[\p{L}\d])(?=\p{Lu}\p{Ll}))/gu, '-').toUpperCase()));