Sometimes, we want to convert strings with hyphenated text to camel case with JavaScript.
In this article, we’ll look at how to convert hyphenated text to camel case with JavaScript.
Use the String.prototype.replace Method
We can use the JavaScript string’s replace
method to replace hyphenated text with camel case.
To do this, we find all the substrings that have the hyphen and a letter after it.
Then we replace that with an upper case letter.
For instance, we can write:
const str = 'my-example-setting'
const camelCased = str
.replace(/-([a-z])/g, (g) => {
return g[1].toUpperCase();
});
console.log(camelCased)
We have the str
string that we want to convert to camel case.
Then we call replace
with a regex that has a hyphen with a letter after it.
The g
flag will search for all instance that match the regex pattern.
The 2nd argument of replace
is a callback that returns the text that we want to replace what’s in the pattern with.
Therefore, camelCased
is ‘myExampleSetting’
.
Lodash camelCase Method
Another way to convert a hyphenated string to a camel-cased string is to use the Lodash camelCase
method.
For instance, we can write:
const str = 'my-example-setting'
const camelCased = _.camelCase(str);
console.log(camelCased)
We pass in the string we want to convert as the argument of camelCase
.
And we get the same result.
Conclusion
We can use the JavaScript string replace
method or the Lodash camelCase
method to convert a hyphenated string to a camel-cased string.