Categories
JavaScript Answers

How to Convert a JavaScript String camelCase to Capital Case?

Spread the love

Sometimes, we want to convert a JavaScript string from camel case to capital case with JavaScript.

In this article, we’ll look at how to convert a JavaScript string from camel case to capital case.

Use the String.prototype.replace Method

We can use the JavaScript string replace method to insert a space between all the words starting with a capital and replace a string’s first character with the upper case version of the character.

To do this, we write:

const str = "thisStringIsGood"
  .replace(/([A-Z])/g, ' $1')
  .replace(/^./, (str) => {
    return str.toUpperCase();
  })
console.log(str)

We call replace with the /([A-Z])/g regex and $1 to add a space before each word that starts with a capital letter.

The g flag gets all instance of strings that match the given pattern.

Then we call replace again to convert the first character of each word to the upper case of the letter.

Therefore, str is:

'This String Is Good'

Use the String.prototype.split and String.prototype.join Methods

Another way to convert a camel case string into a capital case sentence is to use the split method to split a string at the start of each word, which is indicated by the capital letter.

Then we can use join to join the words with a space character.

To do this, we write:

const splitCamelCaseToString = (s) => {
  return s
    .split(/(?=[A-Z])/)
    .map((p) => {
      return p[0].toUpperCase() + p.slice(1);
    })
    .join(' ');
}
const str = splitCamelCaseToString("thisStringIsGood")
console.log(str)

We call split with the /(?=[A-Z])/ regex to split the string into words where the capital letter indicates the start of the word.

Then we call map to convert the string to start with an upper case letter.

And then we call join to join each word together with a space character.

Therefore, str is:

'This String Is Good'

Conclusion

We can use various string and array methods to convert a string from camel case to a capital case sentence.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *