Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hyphenated string to CamelCase

Tags:

regex

clojure

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?

like image 230
Chiron Avatar asked Jun 16 '13 22:06

Chiron


3 Answers

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.

like image 53
ntalbs Avatar answered Oct 06 '22 22:10

ntalbs


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.

like image 38
ToBeReplaced Avatar answered Oct 06 '22 21:10

ToBeReplaced


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)))))) 
like image 21
Shlomi Avatar answered Oct 06 '22 20:10

Shlomi