Converting any string into camel case with JavaScript removing whitespace as well

In JavaScript, camel case formatting converts strings by lowercasing the first letter and capitalizing the first letter of each subsequent word, while removing all whitespace.

What is Camel Case?

Camel case is a naming convention where the first word starts with a lowercase letter and each subsequent word starts with an uppercase letter, with no spaces or punctuation. For example: "hello world" becomes "helloWorld".

Using Regular Expression Method

The most efficient approach uses a regular expression with the replace() method to transform the string:

function convertStringToCamelCase(sentence) {
    return sentence.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, 
    function(match, index) {
        if (+match === 0) return ""; // Remove spaces
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

console.log(convertStringToCamelCase("Add two variables"));
console.log(convertStringToCamelCase("hello world example"));
console.log(convertStringToCamelCase("JavaScript is awesome"));
addTwoVariables
helloWorldExample
javaScriptIsAwesome

Using Split and Join Method

An alternative approach splits the string into words, transforms each word, and joins them:

function toCamelCase(str) {
    return str.split(' ')
        .map((word, index) => {
            if (index === 0) {
                return word.toLowerCase();
            }
            return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
        })
        .join('');
}

console.log(toCamelCase("convert this string"));
console.log(toCamelCase("Multiple Word String"));
convertThisString
multipleWordString

Handling Edge Cases

A robust function should handle various input scenarios:

function robustToCamelCase(str) {
    if (!str) return "";
    
    return str.trim()
        .split(/\s+/)
        .map((word, index) => {
            if (index === 0) {
                return word.toLowerCase();
            }
            return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
        })
        .join('');
}

console.log(robustToCamelCase("  extra   spaces  "));
console.log(robustToCamelCase(""));
console.log(robustToCamelCase("singleword"));
extraSpaces

singleword

Comparison

Method Performance Readability Edge Case Handling
Regular Expression Fast Complex Good
Split and Join Moderate High Excellent

Conclusion

Use the split-and-join method for better readability and maintainability. For performance-critical applications, the regular expression approach offers faster execution while handling whitespace removal effectively.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements