Search code examples
javascriptencodeuricomponent

encodeURIComponent but in lowercase


I have some requirements which would be easily fulfilled by using the encodeURIComponent straight up, but life is never easy, because of the particular workings of this client's system, we need to encode things that come from a database in a url format (e.g. products/household+products/) and turn it into a storage blob which has to follow the 'encoded' format (products%2Fhousehold%2Bproducts%2F), however, it has to be lower case (%2F -> %2F).

The second however comes where the client also has regionalised pages and those have to remain uppercase (e.g. products/GB/household+products). That GB has to remain uppercase so I can't carpet bomb the whole thing with .toLowerCase()

Any thoughts?


Solution

  • You can use a regex to match the encoded "bytes" and convert them to lowercase:

    function encode(text) {
        const uriEncoded = encodeURIComponent(text);
        return uriEncoded.replace(/%\w\w/g, match => match.toLowerCase());
    }
    

    Which produces:

    > encode("products/GB/household+products")
    'products%2fGB%2fhousehold%2bproducts'
    

    You can see that GB is preserved while %2f and %2b are lowercase.

    It is also easy to decode, use the same approach but you first have to convert to uppercase and then decode normally.