I am looking to trim the last two characters of a string in solidity.

For instance:

 string = "Johnny";

I would like to trim the "ny" and end up with

 string = "John";


2 Answers 2


Doing this correctly will require a fairly sophisticated string library, as characters in a string are represented in UTF-8, and have varying lengths. There are a number of string libraries available, but I'm not sure if any of them will give you a substring without modification.

If you are confident you will only be dealing with characters represented in UTF-8 as a single byte (basically Latin letters and numbers and some symbols) you can use the method described in this answer: Substring in solidity

Note that in most cases it's preferable to perform operations like string manipulation outside your contract (for example in your JavaScript application) and pass either the pre-formatted content or its hash to the contract.


Here's a shorter, gas-efficient answer without for loops:

function trim(string calldata str, uint start, uint end) external pure returns(string memory) {
    return str[start:end];

This takes a string and start and end positions to trim the given string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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