2

replace-string has the DELIMITED parameter, which can be used to replace only whole words. replace-in-string does not have such a parameter. Is there an easy work-around besides creating a temporary buffer and using replace-string?

2

I don't know the function replace-in-string, but assuming it uses emacs regex (or using replace-regexp-in-string) you should be able to use word boundaries. You could match foo by using \bfoo\b (or in a string "\\bfoo\\b").

For example, evaluating (replace-regexp-in-string "\\bfoo\\b" "bar" "afoo foob foo moo") would result in the string "afoo foob bar moo".

See here for a detailed description.

1

Based on the answer of @theldoria, here is the function:

(defun replace-in-string-whole-words(what with in)
  "Like 'replace-in-string, but replaces whole words."
  (replace-regexp-in-string (concat "\\b" what "\\b")  with in))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.