Languages
[Edit]
EN

Bash - JavaScript encodeURIComponent equivalent

8 points
Created by:
Mark-Rotteveel
267

In this short article, we would like to show how in Bash, create JavaScript encodeURIComponent() function equivalent to escape all unsafe characters in some URL.

Note: the below example allows to encode Unicode characters too.

Practical example:

#!/bin/bash

function create_utf8_code()
{
	local code="$(echo -n "$1" | xxd -ps)"
	local length="${#code}"

	local i

	for (( i = 0; i < length; i += 2 ))
	do
		echo -n "%${code:$i:2}" | tr '[:lower:]' '[:upper:]'
	done
}

function encode_uri_component()
{
	local text="${1}"
	local length="${#text}"

	local i char

	for (( i = 0; i < length; ++i ))
	do
		char="${text:$i:1}"
		[[ "$char" =~ [-_.!~*\'()a-zA-Z0-9] ]] && echo -n "$char" || create_utf8_code "$char"
	done
}


# Usage example 1:

text="Hi! How are you? Dangerous characters: ?#&"
encoded_text="$(encode_uri_component "$text")"

echo "$encoded_text"  # Hi!%20How%20are%20you%3f%20Dangerous%20characters%3a%20%3f%23%26


# Usage example 2:

#   Not escaped characters:

echo $(encode_uri_component "0123456789")                  # 0123456789
echo $(encode_uri_component "abcdefghijklmnopqrstuvwxyz")  # abcdefghijklmnopqrstuvwxyz
echo $(encode_uri_component "ABCDEFGHIJKLMNOPQRSTUVWXYZ")  # ABCDEFGHIJKLMNOPQRSTUVWXYZ
echo $(encode_uri_component "~!*-_.'()")                   # ~!*-_.'()

#   Some escaped characters:

echo $(encode_uri_component "日本")             # %E6%97%A5%E6%9C%AC
echo $(encode_uri_component "Россия")           # %D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F
echo $(encode_uri_component "ąćęłńóśźż")        # %C4%85%C4%87%C4%99%C5%82%C5%84%C3%B3%C5%9B%C5%BA%C5%BC
echo $(encode_uri_component "@:/?#&=")          # %40%3A%2F%3F%23%26%3D
echo $(encode_uri_component "🚀🍏🍌❤️💻🙂")  # %F0%9F%9A%80%F0%9F%8D%8F%F0%9F%8D%8C%E2%9D%A4%EF%B8%8F%F0%9F%92%BB%F0%9F%99%82
echo $(encode_uri_component $' \t\n')           # %20%09%0A

Output:

Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26
0123456789
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
~!*-_.'()
%E6%97%A5%E6%9C%AC
%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F
%C4%85%C4%87%C4%99%C5%82%C5%84%C3%B3%C5%9B%C5%BA%C5%BC
%40%3A%2F%3F%23%26%3D
%F0%9F%9A%80%F0%9F%8D%8F%F0%9F%8D%8C%E2%9D%A4%EF%B8%8F%F0%9F%92%BB%F0%9F%99%82
%20%09%0A

See also

  1. JavaScript - encode / escape URL characters - Dirask

References

  1. encodeURIComponent() - JavaScript | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join