I've been trying to get a JavaScript regex command to turn something like EYDLessThan5Days into EYD Less Than 5 Days. Any ideas?
The code I used :
"EYDLessThan5Days"
.replace(/([A-Z])/g, ' $1')
.replace(/^./, function(str){ return str.toUpperCase(); });
Out: E Y D Less Than5 Days
But still give me wrong result.
Please help me. Thanks.
Try the following function, it's made to work with all kinds of strings you can throw at it. If you find any defects please point it out in the comments.
function camelPad(str){ return str
// Look for long acronyms and filter out the last letter
.replace(/([A-Z]+)([A-Z][a-z])/g, ' $1 $2')
// Look for lower-case letters followed by upper-case letters
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
// Look for lower-case letters followed by numbers
.replace(/([a-zA-Z])(\d)/g, '$1 $2')
.replace(/^./, function(str){ return str.toUpperCase(); })
// Remove any white space left around the word
.trim();
}
// Test cases
document.body.appendChild(document.createTextNode(camelPad("EYDLessThan5Days")));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(camelPad("LOLAllDayFrom10To9")));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(camelPad("ILikeToStayUpTil9O'clock")));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(camelPad("WhatRYouDoing?")));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(camelPad("ABC")));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(camelPad("ABCDEF")));
This will work for you
"EYDLessThan5Days".replace(/([A-Z][a-z])/g,' $1').replace(/(\d)/g,' $1');
will give you "EYD Less Than 5 Days"
replace(/([A-Z][a-z])/g,' $1')
If a Upper case letter followed by lower case letters, add space before that
replace(/(\d)/g,' $1')
If there is a number add space before that.
Was looking for solution and stumbled upon this post. Ended up using lodash.
For those who don't want to use Regex, there is a method in lodash library called "startCase"
https://lodash.com/docs/4.17.15#startCase
_.startCase('EYDLessThan5Days'); // "EYD Less Than 5 Days"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With