Function: string-replace
string-replace is a byte-compiled function defined in subr.el.gz.
Signature
(string-replace FROM-STRING TO-STRING IN-STRING)
Documentation
Replace FROM-STRING with TO-STRING in IN-STRING each time it occurs.
Other relevant functions are documented in the string group.
Probably introduced at or before Emacs version 28.1.
Shortdoc
;; string
(string-replace "foo" "bar" "foozot")
=> "barzot"
Aliases
Source Code
;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defun string-replace (from-string to-string in-string)
"Replace FROM-STRING with TO-STRING in IN-STRING each time it occurs."
(declare (pure t) (side-effect-free t))
(when (equal from-string "")
(signal 'wrong-length-argument '(0)))
(let ((start 0)
(result nil)
pos)
(while (setq pos (string-search from-string in-string start))
(unless (= start pos)
(push (substring in-string start pos) result))
(push to-string result)
(setq start (+ pos (length from-string))))
(if (null result)
;; No replacements were done, so just return the original string.
in-string
;; Get any remaining bit.
(unless (= start (length in-string))
(push (substring in-string start) result))
(apply #'concat (nreverse result)))))