Lesser known Clojure: new string functions in Clojure 1.8


The latest version of Clojure (1.8) introduced a new set of functions operating on strings. Those functions are only a syntactic sugar. All of its functionality can be achieved with Java methods, but they make our code more idiomatic and easier to read. For clarity’s sake I will list all of them with its doc strings and some examples.

index-of

(index-of s value)
(index-of s value from-index)

Return index of value (string or char) in s, optionally searching
forward from from-index or nil if not found.
(index-of "Clojure is fun. Let's have fun" "fun")
;; => 11

(index-of "Clojure is fun. Let's have fun" "fun" 14)
;; => 14

It is worth noting that index-of is case sensitive:

(index-of "Clojure is fun. Let's have fun" "clojure")
;; => nil

(index-of "Clojure is fun. Let's have fun" "Clojure")
;; => 0

last-index-of

(last-index-of s value)
(last-index-of s value from-index)

Return last index of value (string or char) in s, optionally
searching backward from from-index or nil if not found.
(last-index-of "some text" "t")
;; => 8

(last-index-of "some text" "t" 6)
;; => 5

same as index-of, the last-index-of is case sensitive:

(last-index-of "some text" "T")
;; => nil

starts-with?

(starts-with? s substr)

True if s starts with substr.
(starts-with? "Clojure is fun" "Clojure")
;; => true

(starts-with? "Clojure is fun" "fun")
;; => false

(starts-with? "Clojure is fun" "clojure")
;; => false

please notice, that again starts-with? is case sensitive.

ends-with?

(ends-with? s substr)

True if s ends with substr.
(ends-with? "Clojure is fun" "fun")
;; => true

(ends-with? "Clojure is fun" "is")
;; => false

(ends-with? "Clojure is fun" "fUn")
;; => false

once again we can see that ends-with? is case sensitive.

includes?

(includes? s substr)

True if s includes substr.
(includes? "Clojure is fun" "is")
;; => true

(includes? "Clojure is fun" "are")
;; => false

(includes? "Clojure is fun" "iS")
;; => false

as you can guess, includes? is also case sensitive.


You may also like

ClojureScript: JavaScript Interop

Lesser known Clojure: variants of threading macro

Template method pattern