Conversion from string to different ways of word combination in JavaScript.
In programming, there are several practices of writing compound words or phrases. These practices are used as conventions in almost every programming language and not fix from one to another. The choice of naming conventions always be a controversial issue, with some are holding theirs to be the best and others to be inferior.
Moving forward, before we can do some string conversion, we need to recognize the case styles first. We will learn 4 different case styles which are:
- Snake case
- Kebab case
- Camel case
- Pascal case
1. Snake case
Photo by David Clode on UnsplashSnake case is the practice of writing compound words in which the words are separated by one underscore character and no spaces. The first letter is either upper- or lowercase. It is commonly used in declaring variable names, function names, and sometimes computer’s filenames.
Example
Hello_worldit_department
2. Kebab case
In Kebab case, all letters are written in lower case and the words are separated by a hyphen or minus sign. The kebab notation is often used as a convention for naming filenames.
Example
football-match
3. Camel case
Camel case describes the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, without intervening spaces or punctuation.
Example
camelCasemyLaptop
4. Pascal case
Pascal case is similar to camel case but the first letter is in uppercase. There is no space and hyphen to separate the words. The pascal case is often used as a convention in creating class in many programming language.
Example
MainBuildingRedDress
Let’s start with the string conversion as we already recognized every case styles above.
String Conversion
In Javascript, there are various ways you can convert a string to the 4 case styles mentioned above. I will share the method that I used which is by using RegEx (regular expression).
You can start by creating a new js file called main.js and run it in your terminal/console window by using the following command:
node main.js1. String to Snake Case
RegEx
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/gResult
2. String to Kebab Case
I use the same RegEx as in conversion to snake case above.
Result
3. String to Camel Case
RegEx
Result
4. String to Pascal Case
RegEx
/\w\S*/gResult
Conclusion
Throughout this article, we have learned on how to distinguish 4 case styles which are often seen in any programming language as a convention.
We also got the idea on how to convert a string to these 4 case styles. If you think this article was helpful, don’t forget to share it with your friends.