简体   繁体   中英

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: EYD 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(/([AZ]+)([AZ][az])/g, ' $1 $2') // Look for lower-case letters followed by upper-case letters .replace(/([az\\d])([AZ])/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"

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM