Elisp: String Functions

By Xah Lee. Date: . Last updated: .

Length, Substring

length
(length SEQUENCE)

Return the length of a Sequence.

(length "abc")
;; 3
substring
(substring STRING &optional FROM TO)

return a substring from position FROM to TO. Position start at 0. By default, TO is to end of string, and FROM is 0. If negative, count from right.

(substring "abc123" 0 3)
;; "abc"

Join Strings, Convert to String

Convert String and Number

Convert String to Codepoints

Split String (String to List)

split-string
(split-string STRING &optional SEPARATORS OMIT-NULLS TRIM)

Split STRING into substrings bounded by matches for SEPARATORS.

;; split string into parts, returns a list
(split-string "xy_007_cat" "_")

Buffer Text to String

String to Buffer

Match String by Regex

string-match
(string-match REGEXP STRING &optional START)

Return the index of beginning of first match in STRING. Return nil if no match.

(let ((case-fold-search t))
  (string-match "3" "xx3x"))
;; 2

Get Regex Captured String

match-string

Replace in String

string-replace

(string-replace FROM-STRING TO-STRING IN-STRING)

new in Emacs 28 (Released 2022-04)

replace-regexp-in-string
(replace-regexp-in-string REGEXP REP STRING &optional FIXEDCASE LITERAL SUBEXP START)
Replace string by regex.
(replace-regexp-in-string "</*div>" "<p>" "<div>something</div>")
;; return
;; "<p>something<p>"

Trim String

These are new in Emacs 24.4 (Released 2014-10) . Before Emacs 28 (Released 2022-04) , you need to first load (require 'subr-x) . 〔see Emacs Version History

String Comparison, Equality Test

Character and String

Other String Functions

To use the following, you may need to first load the lib:

(require 'subr-x)

Misc String Functions

Letter Case

Case Table

Reference

Emacs Lisp, String