Here is a handy trick I saw in some code recently. It turns out you can use a negative integer in the count
argument of the left()
and right()
functions in CFML. This works in multiple versions of both Lucee and Adobe ColdFusion!
Here's an example:
left("Peter", -1)
This will trim 1
character off the end of the string. The result of the above code would be:
Pete
I would normally write that as:
left(name, len(name)-1)
The thing to be aware of with the above approach is that if the length of the string is 1, then it would effectively be like calling left(name, 0)
, which does not result in an empty string, it results in an exception. Suppose I'm writing code to trim off a trailing slash, you might write it like this:
if (right(path, 1) == "/") { if (len(path) == 1) { path = ""; } else { path = left(path, len(path)-1); } }
Or using the negative count you could write it like this:
if (right(path, 1) == "/") { path = left(path, -1); }
Trimming Prefixes With Right
Now suppose you wanted to trim the prefix off a string, you can use the right function with a negative integer to do this:
right("https://example.com", -8)
This will trim off the first 8 characters, or https://
and return just:
example.com
Gotcha's
If you do end up using this feature there are a few things to beware of. First this feature is documented in Lucee's docs, it says:
A negative value of n will return (length - n) characters from the beginning of the string.
However Adobe's docs for these functions state that the count argument should be a positive integer. So it is possible though unlikely that it could change to throw an exception in the future.
Second if you pass in a negative value longer than the string length you will see some potentially unexpected results.
Comments
For whatever reason, thinking about negative numbers with left/right just messes up my brain :D I've tried to use it a few times, but I always have to stop and remind myself what it is doing.