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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With