Breaking camelCase syntax in JavaScript

We need to write a JavaScript function that takes a camelCase string and converts it into a readable format by adding spaces before uppercase letters.

Our function should construct and return a new string that splits the input string using a space between words.

Problem Example

For example, if the input to the function is:

Input

const str = 'thisIsACamelCasedString';

Expected Output

'this Is A Camel Cased String'

Solution Using String Iteration

The approach iterates through each character and adds a space before uppercase letters (except the first character):

const str = 'thisIsACamelCasedString';

const breakCamelCase = (str = '') => {
    const isUpper = (char = '') => char.toLowerCase() !== char.toUpperCase() && char === char.toUpperCase();
    let res = '';
    const { length: len } = str;
    
    for(let i = 0; i 

this Is A Camel Cased String

Alternative Solution Using Regular Expression

A more concise approach using regex to match uppercase letters and replace them with a space plus the letter:

const str = 'thisIsACamelCasedString';

const breakCamelCaseRegex = (str = '') => {
    return str.replace(/([A-Z])/g, ' $1');
};

console.log(breakCamelCaseRegex(str));
console.log(breakCamelCaseRegex('javaScriptIsAwesome'));
console.log(breakCamelCaseRegex('HTMLParser'));
this Is A Camel Cased String
java Script Is Awesome
H T M L Parser

How It Works

The first solution uses a helper function isUpper() to check if a character is uppercase by comparing it with its lowercase and uppercase versions. It then iterates through the string and adds a space before each uppercase letter (except at the beginning).

The regex solution uses the pattern /([A-Z])/g to find all uppercase letters and replaces each with a space followed by the letter itself using ' $1'.

Comparison

Method Performance Readability Code Length
String Iteration Faster Medium Longer
Regular Expression Slower High Shorter

Conclusion

Both methods effectively break camelCase strings into readable format. The regex approach is more concise and readable, while the iteration method offers better performance for large strings.

Updated on: 2026-03-15T23:19:00+05:30

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements