DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #95 - CamelCase Method

Write simple .camelCase method (camel_case function in PHP, CamelCase in C# or camelCase in Java) for strings. All words must have their first letter capitalized without spaces.

For instance:

camelcase("hello case") => HelloCase
camelcase("camel case word") => CamelCaseWord


This challenge comes from bestwebua on CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (25)

Collapse
 
savagepixie profile image
SavagePixie • Edited

Replace to the rescue!

const camelCase = str => str.replace(/\s([a-z])/g, (_, x) => x.toUpperCase())
Collapse
 
rafaacioly profile image
Rafael Acioly

very clever :)

Collapse
 
qm3ster profile image
Mihail Malo

Doesn't match the first word, should be /(?:^|\s)([a-z])/g for that or something.

Collapse
 
savagepixie profile image
SavagePixie • Edited

I don't capitalise the first word of a camelCase construct. As far as I'm aware, it isn't customary in JavaScript.

But you are right, if one were to capitalise the first word as well, the regular expression would have to be modified accordingly.

Thread Thread
 
avalander profile image
Avalander

The confusion is because the description says camelCase but they mean PascalCase.

Collapse
 
ynndvn profile image
La blatte

Here comes a naive oneliner:

camel=s=>s.split` `.map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join``
Enter fullscreen mode Exit fullscreen mode

For every word, it uppercases its first letter and lowercases the following ones

Collapse
 
balajik profile image
Balaji K

Nice one liner :). But if s is an empty string, then str[0] will be undefined and toUpperCase will throw an error.

Collapse
 
jacobmgevans profile image
Jacob Evans

It's not about finding edge cases. This is a great solution for a coding challenge... Most coding challenges are things you'd put in production anyways

Collapse
 
kvharish profile image
K.V.Harish

My solution in js

const camelCase = (words = '') => words.split(' ')
                                       .map(word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`)
                                       .join('');
Collapse
 
asfo profile image
Asfo • Edited

Maybe not the best option :) but it works.
JS:

const camelCase = (str) => { if(typeof str !== 'string') { throw 'Not a string'; } return str.trim().toLowerCase().split(' ').map(el => { return el[0].toUpperCase() + el.slice(1); }).join(''); }
Collapse
 
rdelga80 profile image
Ricardo Delgado • Edited

JS

var camelcase = (s) => {
    var o = new Object(s)
    return o.split` `
                 .map(p => p.split``
                       .map((q, i) => i === 0 ? q.toUpperCase(): q)
                                .join``)
                                        .join``
}
Collapse
 
blessedtawanda profile image
Blessed T Mahuni

A beginner solution

function camelCase(stringToBeCamelCased) {
  let wordsArr = stringToBeCamelCased.split(' ')
  let casedWordsArr = []
  for (const word of wordsArr) {
    let casedWord = []
    for (let i = 0; i < word.length; i++) {
      if(i == 0)
        casedWord.push(word[i].toUpperCase())
      else
        casedWord.push(word[i])
    }
    casedWordsArr.push(casedWord.join(''))
  }

  return casedWordsArr.join('')
}

// refined

function camelCaseV2(stringToBeCamelCased) {
  let casedWordsArr = []
  stringToBeCamelCased.split(' ').forEach(word => {
    casedWordsArr.push(word[0].toUpperCase() + word.slice(1))
  })
  return casedWordsArr.join('')
}


Collapse
 
aminnairi profile image
Amin

Haskell

import Data.Char

(|>) = flip ($)

split :: String -> [String]
split [] = [""]
split (character : characters)
    | character == ' ' = "" : rest
    | otherwise = (character : head rest) : tail rest
    where rest = split characters

uppercase :: String -> String
uppercase string =
    map toUpper string

lowercase :: String -> String
lowercase string =
    map toLower string

capitalize :: String -> String
capitalize string =
    uppercase firstCharacter ++ lowercase remainingCharacters
    where
        firstCharacter :: String
        firstCharacter = take 1 string

        remainingCharacters :: String
        remainingCharacters = drop 1 string

join :: [String] -> String
join strings =
    foldl (++) "" strings

camelcase :: String -> String
camelcase string =
    string
        |> split
        |> map capitalize
        |> join

main :: IO ()
main = do
    print $ camelcase "hello case"      -- HelloCase
    print $ camelcase "camel case word" -- CamelCaseWord

Source-Code

Available on repl.it.

Collapse
 
opensussex profile image
gholden
  const camelcase = (stringToConvert) => {
    const stringArray = stringToConvert.trim().split(" ")
    const camel =  stringArray.map(indie => {
      return indie[0].toUpperCase() + indie.slice(1)
    })
    return camel.join('');
  }
Collapse
 
willsmart profile image
willsmart

I agree with SavagePixie. replace is the way to go if you're in JS!

Here's an extended version that covers all the cases I can think of...

const toUpperCamelCase = str => str.replace(
  /[^a-zA-Z]*([a-zA-Z]?)([a-z]+|[A-Z]*)/g,
  (_, firstLetter, rest) => firstLetter.toUpperCase() + rest.toLowerCase()
);

> [
  'Fudge And Sprite', // Words
  'fudge and sprite', // words
  'fudge-and-sprite', // kebab-case
  'fudge_and_sprite', // underscore_case
  'fudgeAndSprite',   // lowerCamelCase
  'FudgeAndSprite',   // UpperCamelCase stays as it is
  'FUDGE_AND_SPRITE', // CONSTANT_CASE
  'fUDGEaNDsPRITE',   // um, uPSIDEDOWNcASE I guess
  '>>> Fudge,    (and SPRITE!)' // or whatevs
].map(toUpperCamelCase);
< ["FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite", "FudgeAndSprite"]

Regex:
Regular expression visualization
test in Debuggex

Collapse
 
rafaacioly profile image
Rafael Acioly
def to_camel_case(value: str) -> str:
    content = value.split(' ')
    return content[0] + ''.join(
        word.title()
        for word in content[1:] 
        if not word.isspace()
    )

This test was easy because i've written a python package that convert snake_case to camelCase and vice-versa :)

github.com/rafa-acioly/animal_case