Categories
JavaScript Answers

How to convert hyphens to camel case with JavaScript?

Spread the love

Sometimes, we want to convert hyphens to camel case with JavaScript.

In this article, we’ll look at how to convert hyphens to camel case with JavaScript.

How to convert hyphens to camel case with JavaScript?

To convert hyphens to camel case with JavaScript, we can use the string replace method.

For instance, we write

const camelCased = myString.replace(/-([a-z])/g, (g) => {
  return g[1].toUpperCase();
});

to call myString.replace with a regex that matches a letter before hyphen and a callback that returns the replacement for the match.

We use -([a-z]) to match a hyphen with a lower case letter after it.

And we use the g flag to return all matches.

Conclusion

To convert hyphens to camel case with JavaScript, we can use the string replace method.

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 *