When I have a string like "Test.m", how can I get just the substring "Test" from that via elisp? I'm trying to use this in my .emacs
file.

- 4,293
- 4
- 36
- 61

- 593
- 3
- 7
- 15
4 Answers
One way is to use substring
(or substring-no-properties
):
(substring "Test.m" 0 -2) => "Test"
(
substring
STRING FROM&optional
TO )Return a new string whose contents are a substring of STRING. The returned string consists of the characters between index FROM (inclusive) and index TO (exclusive) of STRING. FROM and TO are zero-indexed: 0 means the first character of STRING. Negative values are counted from the end of STRING. If TO is
nil
, the substring runs to the end of STRING.

- 3,930
- 1
- 33
- 37
Stefan's answer is idiomatic, when you just need a filename without extension. However, if you manipulate files and filepaths heavily in your code, i recommend installing Johan Andersson's f.el
file and directory API, because it provides many functions absent in Emacs with a consistent API. Check out functions f-base
and f-no-ext
:
(f-base "~/doc/index.org") ; => "index"
(f-no-ext "~/doc/index.org") ; => "~/doc/index"
If, instead, you work with strings often, install Magnar Sveen's s.el
for the same reasons. You might be interested in s-chop-suffix
:
(s-chop-suffix ".org" "~/doc/index.org") ; => "~/doc/index"
For generic substring retrieval use dkim's answer.

- 1
- 1

- 17,660
- 12
- 105
- 166
-
This is a nice high-level solution. Thanks. – Jabba Oct 23 '14 at 19:33
-
Just for basic substrings from directories and file names, there are the `File Name Components` functions in elisp https://www.gnu.org/software/emacs/manual/html_node/elisp/File-Name-Components.html – santiagopim Aug 11 '19 at 22:58
Probably the most flexible option (although it's not clear if you need flexibility) would be to use replace-regexp-in-string
:
See C-hf replace-regexp-in-string
RET
e.g.:
(replace-regexp-in-string "\\..*" "" "Test.m")

- 71,335
- 11
- 153
- 198