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
 
jrswab profile image
J. R. Swab • Edited

How about in Go?

func camelcase(s string) string {
    var cameled string
    split := strings.Fields(s)

    for _, v := range split {
        cameled = fmt.Sprintf("%s%s", cameled, strings.Title(v))
    }
    return cameled
}

Playground

Collapse
 
denolfe profile image
Elliot DeNolf

Crystal

def to_camel(input : String)
  input.split(" ").map(&.capitalize).join
end

Tests

describe "to_camel" do
  it "handles 1 word" do
    to_camel("hello").should eq "Hello"
  end

  it "handles 2 words" do
    to_camel("hello world").should eq "HelloWorld"
  end

  it "handles empty string" do
    to_camel("").should eq ""
  end

  it "handles extra whitespace" do
    to_camel("  hello  world  ").should eq "HelloWorld"
  end
end
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('');
  }