Split pascal case in Javascript (specific case)

I am trying to get a JavaScript regex command to turn something like EYDLessThan5Days into EYD in less than 5 days . Any ideas?

The code I used:

"EYDLessThan5Days"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); });

      

Out: EYD Less Than5 Days

But still give me the wrong result.

Please help me. Thank.

+3


source to share


2 answers


Try the following function to make it work for all types of strings you can throw at it. If you find any flaws, please point 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")));
      

Run codeHide result


+5


source


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 am I doing here



replace(/([A-Z][a-z])/g,' $1')

      

If uppercase letters are followed by lowercase letters, add a space before that

replace(/(\d)/g,' $1')

      

If there is a space before it, add a space.

+4


source







All Articles