A case-insensitive filter in Clojure / ClojureScript

百般思念 提交于 2019-12-05 16:54:28

In Clojure itself you would normally do this with a regular expression. In Java regular expressions you can do this by giving in a flag for case-insensitivity for the match you want to make, or at the start of the regex for global case-insensitivity:

  (filter #(re-find #"(?i)a" %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

Pure Javascript regular expressions only support global flags. They are given in as string as the second parameter to the regex constructor:

  (filter #(re-find (js/RegExp. "a" "i") %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

However, as convenience and to keep the regexes between Java and Javascript similar, the Clojurescript reader translates global java style flags (those at the start of the regex) to their Javascript global equivalent.

So the first example works in Clojurescript as well. Be aware though that non-global flags won't work in Clojurescript where they would work in Clojure.

(defn list-data [alist filter-text]
 (if-let [filter-text (some-> filter-text not-empty .toLowerCase)]
   (filter #(-> % 
                .toLowerCase 
                (.indexOf filter-text)
                (not= -1)) 
           alist)
   alist))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!