Add Space In Camel Case Javascript

4 min read Jun 22, 2024
Add Space In Camel Case Javascript

Add Space in Camel Case JavaScript

In JavaScript, camel case is a common naming convention where words are joined together without spaces or underscores. For example, firstName is written in camel case. However, sometimes we need to convert camel case strings to human-readable format with spaces between words.

Here are several ways to add spaces in camel case strings in JavaScript:

1. Using Regular Expression and Replace Method

This approach utilizes regular expression and the replace method to insert spaces before uppercase letters.

function addSpaces(str) {
  return str.replace(/([A-Z])/g, ' $1');
}

let camelCaseStr = "firstName";
let spacedStr = addSpaces(camelCaseStr);
console.log(spacedStr); // Output: "first Name"

Explanation:

  • str.replace(/([A-Z])/g, ' $1') replaces every uppercase letter ([A-Z]) with a space followed by the uppercase letter itself ( $1).
  • The g flag ensures that all occurrences of uppercase letters are replaced, not just the first one.

2. Using String Split and Join Methods

This method breaks down the camel case string into an array of words and then joins them back together with spaces.

function addSpaces(str) {
  let words = str.split(/(?=[A-Z])/);
  return words.join(' ');
}

let camelCaseStr = "firstName";
let spacedStr = addSpaces(camelCaseStr);
console.log(spacedStr); // Output: "first Name"

Explanation:

  • str.split(/(?=[A-Z])/) splits the string at every point where a capital letter is encountered. This is done using a lookahead regular expression (?=[A-Z]) that matches the position before an uppercase letter but doesn't include it in the split result.
  • words.join(' ') joins the elements of the words array with spaces in between.

3. Using a Loop and Character Check

This approach iterates through each character of the string and adds a space before an uppercase letter.

function addSpaces(str) {
  let spacedStr = "";
  for (let i = 0; i < str.length; i++) {
    if (i > 0 && str[i] === str[i].toUpperCase()) {
      spacedStr += " ";
    }
    spacedStr += str[i];
  }
  return spacedStr;
}

let camelCaseStr = "firstName";
let spacedStr = addSpaces(camelCaseStr);
console.log(spacedStr); // Output: "first Name"

Explanation:

  • The loop iterates through the string, character by character.
  • If the current character is uppercase and not the first character, a space is added to spacedStr.
  • The current character is then added to spacedStr.

These methods provide various ways to add spaces in camel case strings in JavaScript. Choose the method that best suits your needs and coding style.