5

I'm trying to convert a hyphenated string to CamelCase string. I followed this post: Convert hyphens to camel case (camelCase)

(defn hyphenated-name-to-camel-case-name [^String method-name]
  (clojure.string/replace method-name #"-(\w)" 
                          #(clojure.string/upper-case (first %1))))


(hyphenated-name-to-camel-case-name "do-get-or-post")
==> do-Get-Or-Post

Why I'm still getting the dash the output string?

Community
  • 1
  • 1
Chiron
  • 20,081
  • 17
  • 81
  • 133
  • You misread what was being used in the replacement function, array indices in JavaScript start at 0 :) – Ja͢ck Jun 17 '13 at 02:05

3 Answers3

7

You should replace first with second:

(defn hyphenated-name-to-camel-case-name [^String method-name]
  (clojure.string/replace method-name #"-(\w)" 
                          #(clojure.string/upper-case (second %1))))

You can check what argument clojure.string/upper-case gets by inserting println to the code:

(defn hyphenated-name-to-camel-case-name [^String method-name]
  (clojure.string/replace method-name #"-(\w)" 
                          #(clojure.string/upper-case
                            (do
                              (println %1)
                              (first %1)))))

When you run the above code, the result is:

[-g g]
[-o o]
[-p p]

The first element of the vector is the matched string, and the second is the captured string, which means you should use second, not first.

ntalbs
  • 28,700
  • 8
  • 66
  • 83
6

In case your goal is just to to convert between cases, I really like the camel-snake-kebab library. ->CamelCase is the function-name in question.

ToBeReplaced
  • 3,334
  • 2
  • 26
  • 42
1

inspired by this thread, you could also do

(use 'clojure.string)

(defn camelize [input-string] 
  (let [words (split input-string #"[\s_-]+")] 
    (join "" (cons (lower-case (first words)) (map capitalize (rest words)))))) 
Shlomi
  • 4,708
  • 1
  • 23
  • 32