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
}
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
}
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 ?"
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
}
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
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)
Why so complicated? Just do:
Lmao didn't think of that... Thanks mate
Not sure what you mean? It does create spaces, just no trailing space (in my opinion that's how it should be).