How to find capitalized words and add a character before that in a given sentence using JavaScript?

When working with strings that contain capitalized words, you might need to insert a character (like a comma) before each capital letter. This is useful for parsing concatenated sentences or formatting text data.

Problem Statement

Given a string with capitalized words, we want to add a comma before each capital letter that appears after another character:

const str = "Connecting to server Connection has been successful We found result";

The goal is to transform this into: "Connecting to server, Connection has been successful, We found result"

Solution Using Regular Expression

We can use a regular expression to find patterns where a character is followed by a capital letter, then replace it with the character plus a comma:

const str = "Connecting to server Connection has been successful We found result";

const addCommaBeforeCapitals = str => {
    let newStr = '';
    const regex = new RegExp(/.[A-Z]/g);
    newStr = str.replace(regex, ',$&');
    return newStr;
};

console.log(addCommaBeforeCapitals(str));
Connecting to server, Connection has been successful, We found result

How the Regular Expression Works

The regex pattern /.[A-Z]/g breaks down as follows:

  • . - Matches any character
  • [A-Z] - Matches any uppercase letter
  • g - Global flag to find all matches

The replacement ',$&' adds a comma before the matched pattern, where $& represents the entire matched string.

Alternative Approach with Lookahead

For more precise control, you can use a positive lookahead to insert commas only before spaces followed by capital letters:

const str = "Connecting to server Connection has been successful We found result";

const addCommaWithLookahead = str => {
    return str.replace(/(?=\s[A-Z])/g, ',');
};

console.log(addCommaWithLookahead(str));
Connecting to server, Connection has been successful, We found result

Handling Edge Cases

Here's a more robust version that handles various scenarios:

const processString = str => {
    // Handle empty or null strings
    if (!str || str.trim() === '') {
        return str;
    }
    
    // Add comma before capital letters that follow lowercase letters or spaces
    return str.replace(/([a-z\s])([A-Z])/g, '$1,$2');
};

// Test with different examples
console.log(processString("HelloWorld"));
console.log(processString("This IsA Test"));
console.log(processString(""));
console.log(processString("ALLCAPS"));
Hello,World
This, Is,A, Test

ALLCAPS

Conclusion

Regular expressions provide an efficient way to insert characters before capitalized words in strings. The key is choosing the right pattern based on your specific requirements and handling edge cases appropriately.

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

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements