DEV Community

Cover image for CamelCase to normal String in JavaScript
Suyash Vashishtha
Suyash Vashishtha

Posted on • Updated on

CamelCase to normal String in JavaScript

In this post we will see how we can turn any camelCase string to normal string in JS JavaScript..

Step 1 - Breaking the Camel Case

Lets take an example - "checkThisOutBro"

Now we want to break this camelCase string to "Check This Out Bro".

So, In order to do this we will use a regex



const camelToFlat=(camel)=>{
    const camelCase =camel.replace(/([a-z])([A-Z])/g, '$1 $2')

    return camelCase
}



Enter fullscreen mode Exit fullscreen mode

this will give us ```check

This Out Bro


hmmmmm, well atleast it is now a simple string, lets improve it better

### Step 2 -  Taking every letter out from this string...

So after getting ```check

 This Out Bro

``` we can use split() function with " " as args to break it down in an array with each word as element.

```javascript



const camelToFlat=(camel)=>{
    const camelCase =camel.replace(/([a-z])([A-Z])/g, '$1 $2').split(" ")

    return camelCase
}




Enter fullscreen mode Exit fullscreen mode

This will return [ 'check', 'This', 'Out', 'Bro' ] as output and we now have an array of words in that camelCase.

"Wow Suyash you said we will be changing camelCase to string , how come it is an array now huh ?"

BigBrainTime

Just wait a min, we will make it a string again but better !

Step 3 - Making each First letter capital this time !

Now as we have an array of words for a string, we can simply run a loop and make every letter or char at 0 index upperCase.




const camelToFlat=(camel)=>{
    const camelCase =camel.replace(/([a-z])([A-Z])/g, '$1 $2').split(" ")

    let flat =""

    camelCase.forEach(word=>{    
        flat = flat + word.charAt(0).toUpperCase() + word.slice(1) + " "
    })  
    return flat
}





Enter fullscreen mode Exit fullscreen mode

After doing this, our function will take every word in camelCase array and convert it's first letter ( at 0 index) capital and join it with others to make an string

Magik
"POOOOOF ! Magic"

And now our output will be Check This Out Bro

Snippet Sauce link for code snippet !


This is commonly used while rendering keys of an object in applications ( Objects.keys(yourObject) returns array ). And generally keys are in camelCase so you want them to be a normal string but with a dynamic way..

If you liked the blog please drop a ❤️

Top comments (3)

Collapse
 
codingjlu profile image
codingjlu

Why so complicated? Just do:

const camelToFlat = c => (c = c.replace(/[A-Z]/g, " $&"), c[0].toUpperCase() + c.slice(1))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
suyashdev profile image
Suyash Vashishtha

Lmao didn't think of that... Thanks mate

Collapse
 
codingjlu profile image
codingjlu

Not sure what you mean? It does create spaces, just no trailing space (in my opinion that's how it should be).