See #UNIX Shell
http://foo bar/
http://foo bar/
http://foo bar/
http://foo bar/
http://foo bar/
"http://foo bar/"
Translation of: C#
-> http://foo bar/
"The unencoded string is Without external libraries:
'Encoded URL: ''Decoded URL: '
-- will print "http://foo bar/""The unencoded string is $unencoded !\n"Translation of: Perl
# => "http://foo bar/"http://foo bar/ google.com/search?q=`Abdu'l-Bahá
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
" => "http%3A%2F%2Ffoo%20bar%2F => http://foo bar/
> coffee foo.coffee http://foo bar/?name=Foo Barson
"http://foo bar/" "google.com/search?q=`Abdu'l-Bahá"
http://foo bar/ google.com/search?q=`Abdu'l-Bahá %25
Using the library ocamlnet from the interactive loop:
not properly encoded: not properly percent-encoded:
[url-decode]
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
Works with: Mac OS X version 10.9+
Works with: iOS version 7+
// version 1.1.2http://foo bar/ google.com/search?q=`Abdu'l-Bahá
34> http_uri:decode("http%3A%2F%2Ffoo%20bar%2F").
"http://foo bar/": (ht:Pack (chop "http%3A%2F%2Ffoo%20bar%2F") T) -> "http://foo bar/"
// Assume sink does UTF8http://foo bar/ google.com/search?q=`Abdu'l-Bahá
USER>Write $ZConvert("http%3A%2F%2Ffoo%20bar%2F", "I", "URL")
http://foo bar/URL$ = URLDecoder("http%3A%2F%2Ffoo%20bar%2F")
Debug URL$ ; http://foo bar/StringTools:-Decode("http%3A%2F%2Ffoo%20bar%2F", encoding=percent);"http://foo bar/"
Works with: g++
" is decoded: "http%3A%2F%2Ffoo%20bar%2F is decoded: http://foo bar/ !
Currently lambdatalk has no builtin primitive for decoding URLs. Let’s define it using Javascript.
: : : : :: :::: :: :::: : -> :: ::
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
(formerly Perl 6)
= < .say .subst( :g,http://foo bar/ google.com/search?q=`Abdu'l-Bahá
url_decode print-r-->/dev/null url_decode url_decode
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
"Encoded URL: ""Decoded URL: "
Encoded URL: http%3A%2F%2Ffoo%20bar%C3%A8%2F Decoded URL: http://foo barè/
http://foo bar/
-- TEST ------------------------------------------------------------------------http://foo bar/
;; universal decoder, works for ASCII and UTF-8;; (source http://www.newlisp.org/index.cgi?page=Code_Snippets)
--
-- demo\rosetta\decode_url.exw
-- ===========================
-- http://foo bar/ google.com/search?q=`Abdu'l-Bahá
class UrlDecode { function : Main(args : String[]) ~ Nil { Net.UrlUtility->Decode("http%3A%2F%2Ffoo%20bar%2F")->PrintLine(); }
}// We need to escape % characters in Wren as % is otherwise used for string interpolation.http://foo bar/ google.com/search?q=`Abdu'l-Bahá
put urlDecode("http%3A%2F%2Ffoo%20bar%2F") & cr & \ urlDecode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")http://foo bar/ google.com/search?q=`Abdu'l-Bah√°
EncodingUtil.urlDecode('http%3A%2F%2Ffoo%20bar%2F', 'UTF-8');
EncodingUtil.urlDecode('google.com/search?q=%60Abdu%27l-Bah%C3%A1', 'UTF-8');http://foo bar/ google.com/search?q=`Abdu'l-Bahá
This code is careful to ensure that any untoward metacharacters in the input string still do not cause any problems.
urlDecode specialMap seqRE replacement modStrallmap convertfromutf-8nobackslashnovariable
http://foo bar/
Java offers the URLDecoder and URLEncoder classes for this specific task.
Alternately, you could use a regular expression capture
/* offset the matched index since were adjusting the string */http://foo bar/ google.com/search?q=`Abdu'l-Bahá
import net.urllib
fn main() { for escaped in [ "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", ] { u := urllib.query_unescape(escaped)? println(u) }
}http://foo bar/ google.com/search?q=`Abdu'l-Bahá
While the default is to decode parameters as UTF-8 (which is the W3C recommendation,) the characters may have been encoded in another encoding scheme, and this can be handled correctly.
URLDecode["google.com/search?q=%60Abdu%27l-Bah%C3%A1","UTF8"]
val finish = fn s:b2s(map(fn x:number(x, 16), rest(split("%", s))))
val decode = fn s:replace(s, re/(%[0-9A-Fa-f]{2})+/, finish)
writeln decode("http%3A%2F%2Ffoo%20bar%2F")
writeln decode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")http://foo bar/ google.com/search?q=`Abdu'l-Bahá
MODULE URLDecoding;
IMPORT URI := URI:String, Out := NPCT:Console;
BEGIN Out.String(URI.Unescape("http%3A%2F%2Ffoo%20bar%2F"));Out.Ln; Out.String(URI.Unescape("google.com/search?q=%60Abdu%27l-Bah%C3%A1"));Out.Ln;
END URLDecoding.http://foo bar/ google.com/search?q=`Abdu'l-Bahá
Use any one of CGI.unescape or URI.decode_www_form_component. These methods also convert “+” to ” “.
# => "http://foo bar/"Works with: Ruby version 1.9.2
# => "http://foo bar/"URI.unescape (alias URI.unencode) still works. URI.unescape is obsolete since Ruby 1.9.2 because of problems with its sibling URI.escape.
( ( decode = decoded hexcode notencoded . :?decoded & whl ' ( @(!arg:?notencoded "%" (% %:?hexcode) ?arg) & !decoded !notencoded chr$(x2d$!hexcode):?decoded ) & str$(!decoded !arg) ) & out$(decode$http%3A%2F%2Ffoo%20bar%2F) );
http://foo bar/
$$ MODE TUSCRIPT url_encoded="http%3A%2F%2Ffoo%20bar%2F" BUILD S_TABLE hex=":%><:><2<>2<%:" hex=STRINGS (url_encoded,hex), hex=SPLIT(hex) hex=DECODE (hex,hex) url_decoded=SUBSTITUTE(url_encoded,":%><2<>2<%:",0,0,hex) PRINT "encoded: ", url_encoded PRINT "decoded: ", url_decoded
encoded: http%3A%2F%2Ffoo%20bar%2F decoded: http://foo bar/
Works with: ksh
urldecode
urldecodehttp%3A%2F%2Ffoo%20bar%2F http://foobar/ urldecodegoogle.com/search?q%60Abdu%27l-Bah%C3%A1 google.com/search?qAbdul-Bahároot@
urldecode -z -i16-i8# bug /usr/bin/sh HP-UX 11.00! -n -z-z"WARNING: invalid % encoding: > -n cho-e hex print-- -n cho-E print-r--
http://foo bar/
Using the built-in URLDecode (http://reference.wolfram.com/language/ref/URLDecode.html) function:
In[]:= URLDecode["http%3A%2F%2Ffoo%20bar%2F"]
Out[]= "http://foo bar/"
In[]:= URLDecode["google.com/search?q=%60Abdu%27l-Bah%C3%A1"]
Out[]= "google.com/search?q=`Abdu'l-Bahá"
In[]:= URLDecode[{"Kurt+G%C3%B6del", "Paul+Erd%C5%91s"}]
Out[]= {"Kurt Gödel", "Paul Erdős"}"http%3A%2F%2Ffoo%20bar%2F".pump(String, // push each char through these fcns: fcn(c){ if(c=="%") return(Void.Read,2); return(Void.Skip,c) },// %-->read 2 chars else pass through fcn(_,b,c){ (b+c).toInt(16).toChar() }) // "%" (ignored) "3"+"1"-->0x31-->"1"http://foo bar/
or use libCurl:
var Curl=Import.lib("zklCurl");
Curl.urlDecode("http%3A%2F%2Ffoo%20bar%2F");http://foo bar/
FUNCTION Url_Decode$(url$) LOCAL result$ SPLIT url$ BY "%" TO item$ SIZE total FOR x = 1 TO total-1 result$ = result$ & CHR$(DEC(LEFT$(item$[x], 2))) & MID$(item$[x], 3) NEXT RETURN item$[0] & result$
END FUNCTION
PRINT Url_Decode$("http%3A%2F%2Ffoo%20bar%2F")
PRINT Url_Decode$("google.com/search?q=%60Abdu%27l-Bah%C3%A1")http://foo bar/ google.com/search?q=`Abdu'l-Bahá
str = "http%3A%2F%2Ffoo%20bar%2F" # "http://foo bar/" L = substr(str,1,i-1) # chars to left of "%" M = substr(str,i+1,2) # 2 chars to right of "%" R = substr(str,i+3) # chars to right of "%xx" str = sprintf("%s%c%s",L,hex2dec(M),R) num = index("0123456789ABCDEF",toupper(substr(s,length(s)))) - 1 return num + (length(s) ? 16*hex2dec(s) : 0)
http%3A%2F%2Ffoo%20bar%2F http://foo bar/
http://foo bar/
Translation of: Phix
sub decode_url$(s$) local res$, ch$ while(s$ <> "") ch$ = left$(s$, 1) if ch$ = "%" then ch$ = chr$(dec(mid$(s$, 2, 2))) s$ = right$(s$, len(s$) - 3) else if ch$ = "+" ch$ = " " s$ = right$(s$, len(s$) - 1) endif res$ = res$ + ch$ wend return res$
end sub
print decode_url$("http%3A%2F%2Ffoo%20bar%2F")
print decode_url$("google.com/search?q=%60Abdu%27l-Bah%C3%A1")F url_decode(s) V r = ‘’ V i = 0 L i < s.len I s[i] == ‘%’ [Byte] b L i < s.len & s[i] == ‘%’ i++ b.append(Int(s[i.+2], radix' 16)) i += 2 r ‘’= b.decode(‘utf-8’) E r ‘’= s[i] i++ R r print(url_decode(‘http%3A%2F%2Ffoo%20bar%2F’)) print(url_decode(‘https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B0%D0%BD%D1%81%D0%BF%D0%B0%D0%B9%D0%BB%D0%B5%D1%80’))
http://foo bar/ https://ru.wikipedia.org/wiki/Транспайлер
This is provided by the casket library (used for web app development).
create buffer 32000 allot
{{ create bit 5 allot : extract ( $c-$a ) drop @+ bit ! @+ bit 1+ ! bit ; : render ( $c-$n ) dup '+ = [ drop 32 ] ifTrue dup 13 = [ drop 32 ] ifTrue dup 10 = [ drop 32 ] ifTrue dup '% = [ extract hex toNumber decimal ] ifTrue ; : <decode> ( $-$ ) repeat @+ 0; render ^buffer'add again ;
---reveal--- : decode ( $- ) buffer ^buffer'set <decode> drop ;
}}
"http%3A%2F%2Ffoo%20bar%2F" decode buffer putsJ does not have a native urldecode (until version 7 when the jhs ide addon includes a jurldecode).
Here is an implementation:
Note that an earlier implementation assumed the j6 implementation of hfd which where hexadecimal letters resulting from hfd were upper case. J8, in contrast, provides a lower case result from hfd. The addition of toupper guarantees the case insensitivity required by RFC 3986 regardless of which version of J you are using. As the parenthesized expression containing hfd is only evaluated at definition time, there’s no performance penalty from the use of toupper.
dim lookUp$( 256) for i =0 to 256 lookUp$( i) ="%" +dechex$( i) next i url$ ="http%3A%2F%2Ffoo%20bar%2F" print "Supplied URL '"; url$; "'" print "As string '"; url2string$( url$); "'" end function url2string$( i$) for j =1 to len( i$) c$ =mid$( i$, j, 1) if c$ ="%" then nc$ =chr$( hexdec( mid$( i$, j +1, 2))) url2string$ =url2string$ +nc$ j =j +2 else url2string$ =url2string$ +c$ end if next j end function
Supplied URL 'http%3A%2F%2Ffoo%20bar%2F'
As string 'http://foo bar/'The library encoding.s7i defines functions
to handle URL respectively percent encoding.
The function fromPercentEncoded
decodes a percend-encoded string.
The function fromUrlEncoded
works like fromPercentEncoded and additionally decodes ‘+’ with a space.
Both functions return byte sequences.
To decode Unicode characters it is necessary to convert them from UTF-8 with fromUtf8 afterwards.
$ include "seed7_05.s7i"; include "encoding.s7i";
const proc: main is func begin writeln(fromPercentEncoded("http%3A%2F%2Ffoo%20bar%2F")); writeln(fromUrlEncoded("http%3A%2F%2Ffoo+bar%2F")); end func;http://foo bar/ http://foo bar/

URL decoding
You are encouraged to solve this task according to the task description, using any language you may know.
This task (the reverse of URL encoding and distinct from URL parser) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
- Test cases
- The encoded string “
http%3A%2F%2Ffoo%20bar%2F” should be reverted to the unencoded form “http://foo bar/“.
- The encoded string “
google.com/search?q=%60Abdu%27l-Bah%C3%A1” should revert to the unencoded form “google.com/search?q=`Abdu'l-Bahá“.
- The encoded string “
%25%32%35” should revert to the unencoded form “%25” and not “%“.
----------------------------------------
-- URL decodes a string
-- @param {string} str
-- @return {string}
----------------------------------------
on urldecode (str) res = "" ba = bytearray() len = str.length repeat with i = 1 to len c = str.char[i] if (c = "%") then -- fastest hex-to-dec conversion hack based on Lingo's rgb object ba.writeInt8(rgb(str.char[i+1..i+2]).blue) i = i + 2 else if (c = "+") then ba.writeInt8(32) else ba.writeInt8(chartonum(c)) end if end repeat ba.position = 1 return ba.readRawString(ba.length)
endput urldecode("http%3A%2F%2Ffoo%20bar%2F")
put urldecode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")-- "http://foo bar/" -- "google.com/search?q=`Abdu'l-Bahá"
code Text=12;
string 0; \use zero-terminated strings
func Decode(S0); \Decode URL string and return its address
char S0;
char S1(80); \BEWARE: very temporary string space returned
int C, N, I, J;
[I:= 0; J:= 0;
repeat C:= S0(I); I:= I+1; \get char if C=^% then \convert hex to char [C:= S0(I); I:= I+1; if C>=^a then C:= C & ~$20; \convert to uppercase N:= C - (if C<=^9 then ^0 else ^A-10); C:= S0(I); I:= I+1; if C>=^a then C:= C & ~$20; C:= N*16 + C - (if C<=^9 then ^0 else ^A-10); ]; S1(J):= C; J:= J+1; \put char in output string
until C=0;
return S1;
];
Text(0, Decode("http%3A%2F%2Ffoo%20bar%2f"))http://foo bar/
Works with: jq version 1.4
If your jq already has “until”, then the definition given below may be omitted.
# Emit . and stop as soon as "condition" is true. def until(condition; next): def u: if condition then . else (next|u) end; u; def url_decode: # The helper function converts the input string written in the given # "base" to an integer def to_i(base): explode | reverse | map(if 65 <= . and . <= 90 then . + 32 else . end) # downcase | map(if . > 96 then . - 87 else . - 48 end) # "a" ~ 97 => 10 ~ 87 | reduce .[] as $c # base: [power, ans] ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)]) | .[1]; . as $in | length as $length | [0, ""] # i, answer | until ( .[0] >= $length; .[0] as $i | if $in[$i:$i+1] == "%" then [ $i + 3, .[1] + ([$in[$i+1:$i+3] | to_i(16)] | implode) ] else [ $i + 1, .[1] + $in[$i:$i+1] ] end) | .[1]; # answer
"http%3A%2F%2Ffoo%20bar%2F" | url_decode
Translation of: Liberty BASIC
Translation of: Pascal
Const alphanum = "0123456789abcdefghijklmnopqrstuvwxyz" Function ToDecimal (cadena As String, base_ As Uinteger) As Uinteger Dim As Uinteger i, n, result = 0 Dim As Uinteger inlength = Len(cadena) For i = 1 To inlength n = Instr(alphanum, Mid(Lcase(cadena),i,1)) - 1 n *= (base_^(inlength-i)) result += n Next Return result End Function Function url2string(cadena As String) As String Dim As String c, nc, res For j As Integer = 1 To Len(cadena) c = Mid(cadena, j, 1) If c = "%" Then nc = Chr(ToDecimal((Mid(cadena, j+1, 2)), 16)) res &= nc j += 2 Else res &= c End If Next j Return res End Function Dim As String URL = "http%3A%2F%2Ffoo%20bar%2F" Print "Supplied URL '"; URL; "'" Print "URL decoding '"; url2string(URL); "'" URL = "google.com/search?q=%60Abdu%27l-Bah%C3%A1" Print !"\nSupplied URL '"; URL; "'" Print "URL decoding '"; url2string(URL); "'" Sleep
PROC Append(CHAR ARRAY s CHAR c) s(0)==+1 s(s(0))=c
RETURN
CHAR FUNC GetCharFromHex(CHAR c1,c2) CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F] BYTE i,res res=0 FOR i=0 TO 15 DO IF c1=hex(i) THEN res==+i LSH 4 FI IF c2=hex(i) THEN res==+i FI OD
RETURN (res)
PROC Decode(CHAR ARRAY in,out) BYTE i CHAR c out(0)=0 i=1 WHILE i<=in(0) DO c=in(i) i==+1 IF c='+ THEN Append(out,' ) ELSEIF c='% THEN c=GetCharFromHex(in(i),in(i+1)) i==+2 Append(out,c) ELSE Append(out,c) FI OD
RETURN
PROC PrintInv(CHAR ARRAY a) BYTE i IF a(0)>0 THEN FOR i=1 TO a(0) DO Put(a(i)%$80) OD FI
RETURN
PROC Test(CHAR ARRAY in) CHAR ARRAY out(256) PrintInv("input ") PrintF(" %S%E",in) Decode(in,out) PrintInv("decoded") PrintF(" %S%E%E",out)
RETURN
PROC Main() Test("http%3A%2F%2Ffoo%20bar%2F") Test("http%3A%2F%2Ffoo+bar%2F*_-.html")
RETURNScreenshot from Atari 8-bit computer
input http%3A%2F%2Ffoo%20bar%2F decoded http://foo bar/ input http%3A%2F%2Ffoo+bar%2F*_-.html decoded http://foo bar/*_-.html
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
url = [ - 'http%3A%2F%2Ffoo%20bar%2F', - 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E', - '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' - ]
loop u_ = 0 to url.length - 1 say url[u_] say DecodeURL(url[u_]) say end u_
return
method DecodeURL(arg) public static Parse arg encoded decoded = '' PCT = '%' loop label e_ while encoded.length() > 0 parse encoded head (PCT) +1 code +2 tail decoded = decoded || head select when code.strip('T').length() = 2 & code.datatype('X') then do code = code.x2c() decoded = decoded || code end when code.strip('T').length() \= 0 then do decoded = decoded || PCT tail = code || tail end otherwise do nop end end encoded = tail end e_ return decodedhttp%3A%2F%2Ffoo%20bar%2F http://foo bar/ mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E mailto:"Ivan Aim" <ivan.aim@email.com> %6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E mailto:"Irma User" <irma.user@mail.com>
Function Len(string) return length in words, so a value 1.5 means 3 bytes
We can add strings with half word at the end of a series of words.
A$=str$(“A”) has a length of 0.5
b$=chr$(a$) revert bytes to words adding zeroes after each character
Module CheckIt { Function decodeUrl$(a$) { DIM a$() a$()=Piece$(a$, "%") if len(a$())=1 then =str$(a$):exit k=each(a$(),2) \\ convert to one byte per character using str$(string) acc$=str$(a$(0)) While k { \\ chr$() convert to UTF16LE \\ str$() convert to ANSI using locale (can be 1033 we can set it before as Locale 1033) \\ so chr$(0x93) give 0x201C \\ str$(chr$(0x93)) return one byte 93 in ANSI as string of one byte length \\ numbers are for UTF-8 so we have to preserve them acc$+=str$(Chr$(Eval("0x"+left$(a$(k^),2)))+Mid$(a$(k^),3)) } =acc$ } \\ decode from utf8 final$=DecodeUrl$("google.com/search?q=%60Abdu%27l-Bah%C3%A1") Print string$(final$ as utf8dec)="google.com/search?q=`Abdu'l-Bahá" final$=DecodeUrl$("http%3A%2F%2Ffoo%20bar%2F") Print string$(final$ as utf8dec)="http://foo bar/"
}
CheckItFeb 26, 2024
При работе с URL-адресами в Bash может возникнуть необходимость закодировать или декодировать адрес. Для этого можно использовать разные инструменты, например, передать URL-адрес в сценарий на языке PHP и выполнить его, но можно решить задачу проще, не прибегая к дополнительным инструментам.
Для работы c URL-адресами предлагаю рассмотреть две функции Bash:
urlencode()– принимает URL-адрес и кодирует его;urldecode()– принимает закодированный URL-адрес и декодирует его.
Для удобства восприятия, названия функций повторяют названия аналогичных функций, доступных в языке PHP.
function urlencode() { # urlencode <string> local LC_ALL=C for (( i = 0; i < ${#1}; i++ )); do : "${1:i:1}" case "$_" in [a-zA-Z0-9.~_-]) printf '%s' "$_" ;; *) printf '%%%02X' "'$_" ;; esac done printf '\n'
}
function urldecode() { # urldecode <string> : "${1//+/ }" printf '%b\n' "${_//%/\\x}"
}Поместив код функций в файл ~/.bashrc, можно вызывать их в сценариях Bash или использовать отдельно, как показано в следующих примерах.
Кодирование URL-адреса, присвоенного переменной URL:
URL="https://мой-сайт.рф/index.php?id=Главная&p=1"
urlencode $URL
Декодирование кодированного URL-адреса, присвоенного переменной URLCODED:
URL="https://мой-сайт.рф/index.php?id=Главная&p=1"
URLCODED=$(urlencode $URL)
urldecode $URLCODED
While the implementation shown for Rexx will also work with ooRexx, this version uses ooRexx syntax to invoke the built-in functions.
/* Rexx */ X = 0 url. = '' X = X + 1; url.0 = X; url.X = 'http%3A%2F%2Ffoo%20bar%2F' X = X + 1; url.0 = X; url.X = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' X = X + 1; url.0 = X; url.X = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' Do u_ = 1 to url.0 Say url.u_ Say DecodeURL(url.u_) Say End u_
Exit
DecodeURL: Procedure Parse Arg encoded decoded = '' PCT = '%' Do label e_ while encoded~length() > 0 Parse Var encoded head (PCT) +1 code +2 tail decoded = decoded || head Select when code~strip('T')~length() = 2 & code~datatype('X') then Do code = code~x2c() decoded = decoded || code End when code~strip('T')~length() \= 0 then Do decoded = decoded || PCT tail = code || tail End otherwise Nop End encoded = tail End e_ Return decodedhttp%3A%2F%2Ffoo%20bar%2F http://foo bar/ mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E mailto:"Ivan Aim" <ivan.aim@email.com> %6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E mailto:"Irma User" <irma.user@mail.com>
Translation of: ooRexx
Tested with the ooRexx and Regina interpreters.
/* Rexx */X
url
XXurlXurlX
XXurlXurlX
XXurlXurlX
u_url
urlu_
DecodeURLurlu_
u_
encoded
decoded
PCT
encoded
VarencodedheadPCTcodetail
decodeddecodedhead
Whencodecode
codecode
decodeddecodedcode
Whencode
decodeddecodedPCT
tailcodetail
Otherwise
encodedtail
decodedhttp%3A%2F%2Ffoo%20bar%2F http://foo bar/ mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E mailto:"Ivan Aim" <ivan.aim@email.com> %6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E mailto:"Irma User" <irma.user@mail.com>
This REXX version is identical to version 1, but with superfluous and dead code removed.
/*REXX program converts a URL─encoded string ──► its original unencoded form. */url
url
url
URLs
jURLs
urlj
decodeURLurlj
encodeddecoded
encoded
varencodedheadcodetail
decodeddecodedhead
Lcode
whenLcodedecodeddecodedcode
whenLdecodeddecoded
tailcodetail
otherwise
encodedtail
decoded- output is identical to the 1st REXX version.
This REXX version is a shorter version of version 2.
/*REXX program converts & displays a URL─encoded string ──► its original unencoded form.*/url url url url jurlj/*process each URL; display blank line.*/urlj/*display the original URL. */URLdecodeurlj/* " " decoded " *//*stick a fork in it, we're all done. */yyy/*get encoded URL from argument list. */yyyyyy/*a special case for an encoded blank. */URL yyy varyyyplaincodeyyy URLURLplain codeURLURLcode URLURLcode URL
- output is identical to the 1st REXX version.
Works with: ALGOL 68G version Any – tested with release 2.8.3.win32
# returns c decoded as a hex digit # PROC hex value = ( CHAR c )INT: IF c >= "0" AND c <= "9" THEN ABS c - ABS "0" ELIF c >= "A" AND c <= "F" THEN 10 + ( ABS c - ABS "A" ) ELSE 10 + ( ABS c - ABS "a" ) FI; # returns the URL encoded string decoded - minimal error handling # PROC url decode = ( STRING encoded )STRING: BEGIN [ LWB encoded : UPB encoded ]CHAR result; INT result pos := LWB encoded; INT pos := LWB encoded; INT max pos := UPB encoded; INT max encoded := max pos - 3; WHILE pos <= UPB encoded DO IF encoded[ pos ] /= "%" AND pos <= max encoded THEN # not a coded character # result[ result pos ] := encoded[ pos ]; pos +:= 1 ELSE # have an encoded character # result[ result pos ] := REPR ( ( 16 * hex value( encoded[ pos + 1 ] ) ) + hex value( encoded[ pos + 2 ] ) ); pos +:= 3 FI; result pos +:= 1 OD; result[ LWB result : result pos - 1 ] END # url decode # ; # test the url decode procedure # print( ( url decode( "http%3A%2F%2Ffoo%20bar%2F" ), newline ) ); print( ( url decode( "google.com/search?q=%60Abdu%27l-Bah%C3%A1" ), newline ) )
http://foo bar/ google.com/search?q=`Abdu'l-Bahá
Let’s get started.
What is URL decoding?
URL decoding is particularly useful when dealing with web addresses that may contain special characters or spaces.
These encoded URLs become a bit complicated to read since there would be a lot of percent signs and numbers.
- Better understanding of the structure of the site
- Navigate its content programmatically with PowerShell
- Ensure links are correctly formatted for users
The encoding replaces the unsafe ASCII character set with a percent sign and two hexadecimal digits.
Anyway, the ins and outs of this is usually for developers. But suffice it to say it’s important in custom scripts.
Sign up for exclusive updates, tips, and strategies
There is an easy way to decode a URL with PowerShell with the use of the UrlDecode method.
Let’s say you have this URL to decode:
https%3A%2F%2Fmrsharepoint.sharepoint.com%2FFinances%2FForms%2FAllItems.aspx
[Net.WebUtility]::UrlDecode("https%3A%2F%2Fmrsharepoint.sharepoint.com%2FFinances%2FForms%2FAllItems.aspx")After pressing enter, the method will convert the percent-encoded URL back to its original, human-readable format.
For this, the decoded URL is now back to the actual URL:

How to Encode a URL Using PowerShell
If you need to learn URL encoding, there is a method called UrlEncode that does the reverse process.
Let’s say you have this URL in its original form to encode:
https://mrsharepoint.sharepoint.com/Finances/Forms/AllItems.aspx
[Net.WebUtility]::UrlEncode("https://mrsharepoint.sharepoint.com/Finances/Forms/AllItems.aspx")After pressing enter, the method will transform the full URL into an encoded string.

Other Methods of Decoding a URL
The methods above are only if you specifically need to use PowerShell.
Usually, this happens when you have to weave the encoding/decoding into a larger script.
But if you want simpler tools, there are a lot of web apps like this one and that one that could encode/decode URLs.
For any business-related queries or concerns, reach out using the contact form here. I always reply.
To explain the error you’re getting, this error happens because PowerShell is assuming that -join is being passed as argument of ForEach-Object this is why you need to wrap your expression with the grouping operator ( ), basically to, as explained in the documentation, “let output from a command participate in an expression“. In addition, hashtables are not enumerable by default in PowerShell, you must use the .GetEnumerator() method:
$formData = @{ 'grant_type' = 'password' 'scope' = 'xyz' 'client_id' = 'xyzAPIClient' 'client_secret' = 'xyzabcdef' 'username' = '[email protected]' 'password' = 'password1'
}
$formUrlEncoded = ($formData.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join '&'
$formUrlEncoded
# Outputs:
# [email protected]&client_id=xyzAPIClient&password=password1&scope=xyz&grant_type=password&client_secret=xyzabcdefTaking a step back, the -Body parameter from Invoke-RestMethod takes IDIctionary as input and already knows how to deal with instances implementing the interface, so it is very likely that you don’t need to join the key / value pairs to form the url-encoded-string.
In summary, it is likely that this should work (as it becomes evident you’re trying to get a token from the Graph API, see the examples from this answer and this answer):
$formData = @{ 'grant_type' = 'password' 'scope' = 'xyz' 'client_id' = 'xyzAPIClient' 'client_secret' = 'xyzabcdef' 'username' = '[email protected]' 'password' = 'password1'
}
$response = Invoke-RestMethod -Uri $apiEndPoint -Method Post -Body $formData -Headers $headersSide note, in case you do need to form the url-encoded-string, using the HttpUtility APIs can be useful here:
Add-Type -AssemblyName System.Web
$query = [System.Web.HttpUtility]::ParseQueryString('')
$formData.GetEnumerator() | ForEach-Object { $query[$_.Key] = $_.Value }
# if you need URL encoded:
$query.ToString()
# username=user1%40xyz.com&client_id=xyzAPIClient&password=password1&scope=xyz&grant_type=password&client_secret=xyzabcdef
# if you need URL decoded:
[System.Web.HttpUtility]::UrlDecode($query.ToString())
# [email protected]&client_id=xyzAPIClient&password=password1&scope=xyz&grant_type=password&client_secret=xyzabcdefIn many projects, you will get requirements to encode and decode strings, and PowerShell is the best option. In this tutorial, I will explain how to use PowerShell to encode and decode strings.
What are the Encoding and Decoding in PowerShell?
What is Encoding?
Encoding is the process of converting data from one form to another. It is often used to ensure data can be safely transmitted or stored. For example, Base64 encoding is a standard method that converts binary data into an ASCII string format.
What is Decoding?
Decoding is the reverse process of encoding. It converts encoded data back into its original form. For instance, decoding a Base64 string will return the original binary data.
There are various methods for encoding and decoding strings in PowerShell. Let us check each one with example and complete script.
I have executed it using VS code, but you can also use Windows PowerShell ISE.
Method 1: Base64 Encoding and Decoding
Base64 Encoding
Base64 encoding is one of the most used methods to encode binary data as text. Here’s a simple example of how to encode a string to Base64 in PowerShell:
# Original string
$originalString = "Hello, PowerShell!"
# Convert the string to bytes
$bytes = [System.Text.Encoding]::UTF8.GetBytes($originalString)
# Encode the bytes to Base64
$base64String = [Convert]::ToBase64String($bytes)
# Output the Base64 encoded string
Write-Output $base64StringSGVsbG8sIFBvd2VyU2hlbGwhYou can see the output in the screenshot below:

Base64 Decoding
# Base64 encoded string
$base64String = "SGVsbG8sIFBvd2VyU2hlbGwh"
# Decode the Base64 string to bytes
$bytes = [Convert]::FromBase64String($base64String)
# Convert the bytes back to the original string
$decodedString = [System.Text.Encoding]::UTF8.GetString($bytes)
# Output the decoded string
Write-Output $decodedStringIn this example, the Base64 string SGVsbG8sIFBvd2VyU2hlbGwh decodes back to Hello, PowerShell!.
Here is the output in the screenshot below:

Method 2: URL Encoding and Decoding
URL Encoding
URL encoding is used to encode special characters in URLs. PowerShell provides a convenient way to perform URL encoding:
# Original URL
$url = "https://powershellfaqs.com/search?query=PowerShell scripting"
# URL encode the string
$encodedUrl = [System.Web.HttpUtility]::UrlEncode($url)
# Output the URL encoded string
Write-Output $encodedUrlURL Decoding
# URL encoded string
$encodedUrl = "https%3a%2f%2fpowershellfaqs.com%2fsearch%3fquery%3dPowerShell+scripting"
# URL decode the string
$decodedUrl = [System.Web.HttpUtility]::UrlDecode($encodedUrl)
# Output the decoded URL
Write-Output $decodedUrlMethod 3: HTML Encoding and Decoding
HTML Encoding
HTML encoding is used to convert characters that have special meanings in HTML into their corresponding HTML entities. Here’s how to encode an HTML string in PowerShell:
# Original HTML string
$htmlString = "<div>PowerShell & Scripting</div>"
# HTML encode the string
$encodedHtml = [System.Web.HttpUtility]::HtmlEncode($htmlString)
# Output the HTML encoded string
Write-Output $encodedHtmlHTML Decoding
To decode an HTML-encoded string back to its original form:
# HTML encoded string
$encodedHtml = "<div>PowerShell & Scripting</div>"
# HTML decode the string
$decodedHtml = [System.Web.HttpUtility]::HtmlDecode($encodedHtml)
# Output the decoded HTML
Write-Output $decodedHtmlConclusion
PowerShell provides different methods to handle Base64, URL, and HTML encoding and decoding.
In this PowerShell tutorial, I explained how to use PowerShell to encode and decode strings.
You may also like:
MATLAB / Octave
us
octave:3> urldecoding('http%3A%2F%2Ffoo%20bar%2F')
ans = http://foo bar/Icon and Unicon
"Improperly encoded string ""encoded = " "decoded = " #: decode URL/URI encoded data # build lookup table for everything # decode every %xx or fail
hexcvt provides hexstring
encoded = "http%3A%2F%2Ffoo%20bar%2F" decoded = "http://foo bar/"




