Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Pascal Case in Javascript (Certain Case)

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.

like image 500
Naval Navc Avatar asked Oct 04 '14 01:10

Naval Navc


3 Answers

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")));
like image 109
SeinopSys Avatar answered Nov 15 '22 05:11

SeinopSys


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"

What I am doing here

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.

like image 33
Mritunjay Avatar answered Nov 15 '22 06:11

Mritunjay


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"
like image 4
AmirA Avatar answered Nov 15 '22 07:11

AmirA