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
.
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.
encode(string_to_encode,space_char)
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.This method returns the encoded version of the said string.
Let’s look at the code below:
include std/net/url.e--declare a string sequencesequence to_be_encode, encoded-- assign valuesto_be_encode = "https://www.google.com/search?chrome&sourceid=me"--make the encoding and save to a variable the returnencoded = encode(to_be_encode, "+")printf(1,"%s",{encoded})
url.e
file to the program.url
to the to_be_encoded
variable.encode()
method to convert the value of to_be_encoded
and save it in the variable encoded
.