Using Regex to Add Spaces Before Capital Letters in a String
04 April, 2023
Quite often as a frontend developer, you will want to use a string returned from an API as a header or a label in one way or another. Perhaps as a tab title or in a card for a dashboard.\
Unfortunately, the API may not be aware of this, nor capable of returning a string formatted in a nice way to allow the label to be human-readable.
Luckily, we can use replace and a regex to format the string in a cleaner way for us to display:
const stringFromApi = 'UserAccountDetails'; const formattedString = stringFromApi.replace(/([a-z])([A-Z])/g, '$1 $2').trim(); console.log(formattedString); // 'User Account Details'
This is a pretty simple regular expression that looks globally in the string for where the lower and uppercase characters are in the string and the replace function second argument puts a space between them.
If you liked this post, please share it!