Wednesday, February 26, 2020

Convert snake case to camelcase for a given string in javaScript |Typescript example

In this blog post, we are going to discuss about snake/camel case tutorials with examples in java script or typescript.

Convert snake case to camel case   in typescript

String is a group of characters which contains word(s).
snake case text is combination words which are are separated by underscore.
for example 
hello_world is a snake case string example.
Important points about snake case sentences
  • no spaces or punctuation in between words
  • words are separated by underscore
  • these are used in declaring variables  and method names in some programming languages
  • first letter can be either uppercase or lower case, but convention approach is first letter is lower case.
camel cases are string words in which first letter is lower case and middle words are upper case.

example camel case strings are firstName, lastName

Important points about camel case sentences
  • spaces and punctuation  are not allowed
  • It will be used in defining variable names in programming languages likes java.
camel cases and snake cases are compound words.
Conversion of camel to snake is a normal task for developers.
typescript is a super set of java script, so java script code works in typescript.

We can do this in many ways, one of the approach is using map() function, other using regular expression.

using map() method

This approach is using two functions
  • given snake case string input is first_name
  • split string into words by separator underscore
  • Iterate each word, returns first word, from second string onwards apply firstUppercase function
  • firstUppercase function is to convert first letter to uppercase and remaining string converted to lower case
let snakeCaseString = "first_name"
const snakeToCamelCase = sentence => sentence
    .split('_')
    .map((word, index) => {
        if (word === 0) {
            return part.toLowerCase();
        }
        return firstUppercase(word);
    })
    .join('');
const firstUppercase = word => word &&
    word.charAt(0).toUpperCase() + word.slice(1);

console.log(snakeCaseString);
console.log(snakeToCamelCase(snakeCaseString));
Output is
first_name
FirstName

Using regular expression

It is very simple using regular expression and performance is best compared with map() function.
  • Given a string snake case string 
  • separate words by separator underscore(_) using regular expression make the second word firstcharacter to upper case.
snakeToCamel = snakeCaseString => snakeCaseString.replace(/([-_]\w)/g, g => g[1].toUpperCase())
console.log(snakeToCamel(snakeCaseString));
Output is

first_name
firstName
Please like and share your feedback if you like this post.

Related article


EmoticonEmoticon