What is the encode() method in Euphoria?

Overview

The encode() method performs a conversion operation on strings. It converts all non-alphanumeric characters to their percent-sign hexadecimal representation and sign for spaces.

It means that special characters in a string are converted to a representational value consisting of a % character and a hexadecimal value. For example, when encoded, the ampersand & character will have this value: %26.

When is the encode() method very useful?

Firstly, we have to include the inbuilt program url.e in our code:

include std/net/url.e
  • The most important use of this method is to encode data sent over a URL to another script or database to avoid harmful script injection. With this method, special characters that might have such an effect are encoded.

  • Apart from the situation mentioned above, it can be used for any other reason we deem necessary.

Syntax

encode(string_to_encode,space_char)

Parameters

  • string_to_encode: This represents any string that we wish to encode. This is usually a URL string as most real project use cases.
  • space_char: This argument is optional. It is the plus + character by default. This plus + sign will be used instead of a space in the encoding process.

Return value

This method returns the encoded version of the said string.

Example

Let’s look at the code below:

include std/net/url.e
--declare a string sequence
sequence to_be_encode, encoded
-- assign values
to_be_encode = "https://www.google.com/search?chrome&sourceid=me"
--make the encoding and save to a variable the return
encoded = encode(to_be_encode, "+")
printf(1,"%s",{encoded})

Explanation

  • Line 1: We include the url.e file to the program.
  • Line 4: We declare two sequence variables.
  • Line 7: We assign the value of a simple google search url to the to_be_encoded variable.
  • Line 10: We use theencode() method to convert the value of to_be_encoded and save it in the variable encoded.
  • Line 11: We use format string printing to display the encoded value to output.

Free Resources