URL encoding: Difference between revisions
→{{header|langur}}
(Added Algol 68) |
Langurmonkey (talk | contribs) |
||
(36 intermediate revisions by 22 users not shown) | |||
Line 26:
;Variations:
* Lowercase escapes are legal, as in "<code><nowiki>http%3a%2f%2ffoo%20bar%2f</nowiki></code>".
* Special characters have different encodings for different standards:
** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~".
** HTML 5, section [http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#url-encoded-form-data 4.10.22.5 URL-encoded form data], says to preserve "-._*", and to encode space " " to "+".
** [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#description encodeURI] function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#".
;Options:
Line 39 ⟶ 41:
* [[URL parser]]
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">F url_encode(s)
V r = ‘’
V buf = ‘’
F flush_buf() // this function is needed because strings in 11l are UTF-16 encoded
I @buf != ‘’
V bytes = @buf.encode(‘utf-8’)
L(b) bytes
@r ‘’= ‘%’hex(b).zfill(2)
@buf = ‘’
L(c) s
I c C (‘0’..‘9’, ‘a’..‘z’, ‘A’..‘Z’, ‘_’, ‘.’, ‘-’, ‘~’)
flush_buf()
r ‘’= c
E
buf ‘’= c
flush_buf()
R r
print(url_encode(‘http://foo bar/’))
print(url_encode(‘https://ru.wikipedia.org/wiki/Транспайлер’))</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo%20bar%2F
https%3A%2F%2Fru.wikipedia.org%2Fwiki%2F%D0%A2%D1%80%D0%B0%D0%BD%D1%81%D0%BF%D0%B0%D0%B9%D0%BB%D0%B5%D1%80
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC MustEncode(CHAR c CHAR ARRAY ex)
BYTE i
IF c>='a AND c<='z OR c>='A AND c<='Z OR c>='0 AND c<='9 THEN
RETURN (0)
FI
IF ex(0)>0 THEN
FOR i=1 TO ex(0)
DO
IF ex(i)=c THEN
RETURN (0)
FI
OD
FI
RETURN (1)
PROC Append(CHAR ARRAY s CHAR c)
s(0)==+1
s(s(0))=c
RETURN
PROC Encode(CHAR ARRAY in,out,ex BYTE spaceToPlus)
CHAR ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
BYTE i
CHAR c
out(0)=0
FOR i=1 TO in(0)
DO
c=in(i)
IF spaceToPlus=1 AND c=32 THEN
Append(out,'+)
ELSEIF MustEncode(c,ex) THEN
Append(out,'%)
Append(out,hex(c RSH 4))
Append(out,hex(c&$0F))
ELSE
Append(out,c)
FI
OD
RETURN
PROC EncodeRaw(CHAR ARRAY in,out)
Encode(in,out,"",0)
RETURN
PROC EncodeRFC3986(CHAR ARRAY in,out)
Encode(in,out,"-._~",0)
RETURN
PROC EncodeHTML5(CHAR ARRAY in,out)
Encode(in,out,"-._*",1)
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)
EncodeRaw(in,out)
PrintInv("encoded ")
PrintF(" %S%E",out)
EncodeRFC3986(in,out)
PrintInv("RFC 3986")
PrintF(" %S%E",out)
EncodeHTML5(in,out)
PrintInv("HTML 5 ")
PrintF(" %S%E%E",out)
RETURN
PROC Main()
Test("http://foo bar/")
Test("http://www.rosettacode.org/wiki/URL_encoding")
Test("http://foo bar/*_-.html")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/URL_encoding.png Screenshot from Atari 8-bit computer]
<pre>
input http://foo bar/
encoded http%3A%2F%2Ffoo%20bar%2F
RFC 3986 http%3A%2F%2Ffoo%20bar%2F
HTML 5 http%3A%2F%2Ffoo+bar%2F
input http://www.rosettacode.org/wiki/URL_encoding
encoded http%3A%2F%2Fwww%2Erosettacode%2Eorg%2Fwiki%2FURL%5Fencoding
RFC 3986 http%3A%2F%2Fwww.rosettacode.org%2Fwiki%2FURL_encoding
HTML 5 http%3A%2F%2Fwww.rosettacode.org%2Fwiki%2FURL_encoding
input http://foo bar/*_-.html
encoded http%3A%2F%2Ffoo%20bar%2F%2A%5F%2D%2Ehtml
RFC 3986 http%3A%2F%2Ffoo%20bar%2F%2A_-.html
HTML 5 http%3A%2F%2Ffoo+bar%2F*_-.html
</pre>
=={{header|Ada}}==
{{libheader|AWS}}
<
with Ada.Text_IO; use Ada.Text_IO;
procedure Encode is
Line 48 ⟶ 190:
begin
Put_Line (AWS.URL.Encode (Normal));
end Encode;</
{{out}}
<pre>http%3A%2F%2Ffoo%20bar%2F</pre>
=={{header|ALGOL 68}}==
<
# encodes the specified url - 0-9, A-Z and a-z are unchanged, #
# everything else is converted to %xx where xx are hex-digits #
Line 86 ⟶ 228:
print( ( encode url( "http://foo bar/" ), newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
Line 93 ⟶ 235:
=={{header|Apex}}==
<
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
=={{header|AppleScript}}==
{{libheader|AppleScript Toolbox}}
<
{{out}}
<pre>"http%3A%2F%2Ffoo%20bar%2F"</pre>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 URL$ = "http://foo bar/"
110 GOSUB 140"URL ENCODE URL$ RETURNS R$
120 PRINT R$;
130 END
140 LET R$ = ""
150 LET L = LEN (URL$)
160 IF NOT L THEN RETURN
170 LET H$ = "0123456789ABCDEF"
180 FOR I = 1 TO L
190 LET C$ = MID$ (URL$,I,1)
200 LET C = ASC (C$)
210 IF C < ASC ("0") OR C > ASC ("Z") + 32 OR C > ASC ("9") AND C < ASC ("A") OR C > ASC ("Z") AND C < ASC ("A") + 32 THEN H = INT (C / 16):C$ = "%" + MID$ (H$,H + 1,1) + MID$ (H$,C - H * 16 + 1,1)
220 LET R$ = R$ + C$
230 NEXT I
240 RETURN</syntaxhighlight>
=={{header|Arturo}}==
<
print encoded</syntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo
=={{header|AutoHotkey}}==
<
; Modified from http://goo.gl/0a0iJq
UriEncode(Uri, Reserved:="!#$&'()*+,/:;=?@[]") {
Unreserved := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
While (Code := NumGet(Var, A_Index - 1, "UChar")) {
If InStr(Unreserved . Reserved, Chr(Code)) {
Encoded .= Chr(Code)
}
Else {
}
}
Return Encoded
}</syntaxhighlight>
=={{header|AWK}}==
<
for (i = 0; i <= 255; i++)
ord[sprintf("%c", i)] = i
Line 157 ⟶ 312:
# Escape every line of input.
{ print escape($0) }</
The array <code>ord[]</code> uses idea from [[Character codes#AWK]].
To follow the rules for HTML 5, uncomment the two lines that convert " " to "+", and use the regular expression that preserves "-._*".
=={{header|Bash}}==
<syntaxhighlight lang="bash">urlencode() {
local LC_ALL=C # support unicode: loop bytes, not characters
local c i n=${#1}
for (( i=0; i<n; i++ )); do
c="${1:i:1}"
case "$c" in
#' ') printf '+' ;; # HTML5 variant
[[:alnum:].~_-]) printf '%s' "$c" ;;
*) printf '%%%02x' "'$c" ;;
esac
done
}
urlencode "http://foo bar/"</syntaxhighlight>
{{out}}
<pre>
http%3a%2f%2ffoo%20bar%2f
</pre>
To produce upper-case hex codes, replace <code>%02x</code> with <code>%02X</code>
See also: [http://mywiki.wooledge.org/BashFAQ/071 BashFAQ/071]
=={{header|BBC BASIC}}==
<
END
Line 176 ⟶ 355:
ENDIF
ENDWHILE
= url$</
{{out}}
<pre>
Line 183 ⟶ 362:
=={{header|Bracmat}}==
<
= encoded exceptions octet string
. !arg:(?exceptions.?string)
Line 224 ⟶ 403:
& out$(encode$("-._~"."http://foo.bar.com/~user-name/_subdir/*~.html"))
);
</syntaxhighlight>
{{out}}
<pre>without exceptions:
Line 245 ⟶ 424:
=={{header|C}}==
<
#include <ctype.h>
Line 278 ⟶ 457:
return 0;
}</
=={{header|C sharp}}==
<
namespace URLEncode
Line 298 ⟶ 477:
}
}
}</
{{out}}
Line 306 ⟶ 485:
=={{header|C++}}==
using Qt 4.6 as a library
<
#include <iostream>
Line 314 ⟶ 493:
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}</
{{out}}
<PRE>http%3A%2F%2Ffoo%20bar%2F</PRE>
Line 320 ⟶ 499:
=={{header|Clojure}}==
Using Java's URLEncoder:
<
(URLEncoder/encode "http://foo bar/" "UTF-8")</
{{out}}<pre>"http%3A%2F%2Ffoo+bar%2F"</pre>
Line 328 ⟶ 507:
=={{header|Common Lisp}}==
<
(not (digit-char-p char 36)))
Line 342 ⟶ 521:
url)))
(url-encode "http://foo bar/")</
{{out}}
<pre>"http%3A%2F%2Ffoo%20bar%2F"</pre>
=={{header|Crystal}}==
The standard library <code>URI</code> class provides methods for both the RFC 3986 and HTML 5 standards. The RFC 3986 method defaults to replacing space characters with <code>%20</code> but will replace them with <code>+</code> instead if the optional parameter <code>space_to_plus</code> is true. The HTML 5 method has the opposite default behavior.
<syntaxhighlight lang="crystal">require "uri"
puts URI.encode("http://foo bar/")
puts URI.encode("http://foo bar/", space_to_plus: true)
puts URI.encode_www_form("http://foo bar/")
puts URI.encode_www_form("http://foo bar/", space_to_plus: false)</syntaxhighlight>
{{out}}
<pre>http://foo%20bar/
http://foo+bar/
http%3A%2F%2Ffoo+bar%2F
http%3A%2F%2Ffoo%20bar%2F</pre>
=={{header|D}}==
<
void main() {
writeln(encodeComponent("http://foo bar/"));
}</
<pre>http%3A%2F%2Ffoo%20bar%2F</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
function EncodeURL(URL: string): string;
var I: integer;
begin
Result:='';
for I:=1 to Length(URL) do
if URL[I] in ['0'..'9', 'A'..'Z', 'a'..'z'] then Result:=Result+URL[I]
else Result:=Result+'%'+IntToHex(byte(URL[I]),2);
end;
procedure EncodeAndShowURL(Memo: TMemo; URL: string);
var ES: string;
begin
Memo.Lines.Add('Unencoded URL: '+URL);
ES:=EncodeURL(URL);
Memo.Lines.Add('Encoded URL: '+ES);
Memo.Lines.Add('');
end;
procedure ShowEncodedURLs(Memo: TMemo);
begin
EncodeAndShowURL(Memo,'http://foo bar/');
EncodeAndShowURL(Memo,'https://rosettacode.org/wiki/URL_encoding');
EncodeAndShowURL(Memo,'https://en.wikipedia.org/wiki/Pikes_Peak_granite');
end;
</syntaxhighlight>
{{out}}
<pre>
Unencoded URL: http://foo bar/
Encoded URL: http%3A%2F%2Ffoo%20bar%2F
Unencoded URL: https://rosettacode.org/wiki/URL_encoding
Encoded URL: https%3A%2F%2Frosettacode%2Eorg%2Fwiki%2FURL%5Fencoding
Unencoded URL: https://en.wikipedia.org/wiki/Pikes_Peak_granite
Encoded URL: https%3A%2F%2Fen%2Ewikipedia%2Eorg%2Fwiki%2FPikes%5FPeak%5Fgranite
Elapsed Time: 11.734 ms.
</pre>
=={{header|Elixir}}==
<
"http%3A%2F%2Ffoo%20bar%2F"</
=={{header|Erlang}}==
Line 386 ⟶ 629:
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
let main args =
printfn "%s" (Uri.EscapeDataString(args.[0]))
0</
{{out}}
<pre>>URLencoding.exe "http://foo bar/"
Line 398 ⟶ 641:
=={{header|Factor}}==
Factor's built-in URL encoder doesn't encode <code>:</code> or <code>/</code>. However, we can write our own predicate quotation that tells <code>(url-encode)</code> what characters to exclude.
<
: my-url-encode ( str -- encoded )
[ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;
"http://foo bar/" my-url-encode print</
{{out}}
<pre>
Line 411 ⟶ 654:
=={{header|Free Pascal}}==
<
var
ch: AnsiChar;
Line 422 ⟶ 665:
Result := Result + ch;
end;
end;</
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">
Dim Shared As String lookUp(256)
For cadena As Integer = 0 To 256
lookUp(cadena) = "%" + Hex(cadena)
Next cadena
Function string2url(cadena As String) As String
Dim As String cadTemp, cadDevu
For j As Integer = 1 To Len(cadena)
cadTemp = Mid(cadena, j, 1)
If Instr( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", cadTemp) Then
cadDevu &= cadTemp
Else
cadDevu &= lookUp(Asc(cadTemp))
End If
Next j
Return cadDevu
End Function
Dim As String URL = "http://foo bar/"
Print "Supplied URL '"; URL; "'"
Print "URL encoding '"; string2url(URL); "'"
Sleep
</syntaxhighlight>
{{out}}
<pre>Supplied URL 'http://foo bar/'
URL encoding 'http%3A%2F%2Ffoo%20bar%2F'</pre>
=={{header|Frink}}==
Frink has a built-in <code>URLEncode[<I>string</I>, <I>encoding="UTF-8"</I>]</code> function that correctly encodes strings (including high Unicode characters) for inclusion in a URL:
<syntaxhighlight lang="frink">println[URLEncode["http://foo bar/"]]</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo+bar%2F
</pre>
=={{header|FutureBasic}}==
<pre>
In addition to the generic alphanumeric character set used in the demo code below, FB offers several special character sets for URL encoding:
fn CharacterSetURLFragmentAllowedSet
fn CharacterSetURLHostAllowedSet
fn CharacterSetURLPasswordAllowedSet
fn CharacterSetURLPathAllowedSet
fn CharacterSetURLQueryAllowedSet
fn CharacterSetURLUserAllowedSet
Users can also create custom character strings with:
fn CharacterSetWithCharactersInString( CFStringRef string ) = CFCharacterSetRef
</pre>
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
local fn PercentEncodeURLString( urlStr as CFStringRef ) as CFStringRef
CFStringRef encodedStr = fn StringByAddingPercentEncodingWithAllowedCharacters( urlStr, fn CharacterSetAlphanumericSet )
end fn = encodedStr
NSLog( @"%@", fn PercentEncodeURLString( @"http://foo bar/" ) )
NSLog( @"%@", fn PercentEncodeURLString( @"http://www.rosettacode.org/wiki/URL_encoding" ) )
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo%20bar%2F
http%3A%2F%2Fwww%2Erosettacode%2Eorg%2Fwiki%2FURL%5Fencoding
</pre>
=={{header|Go}}==
<
import (
Line 434 ⟶ 753:
func main() {
fmt.Println(url.QueryEscape("http://foo bar/"))
}</
{{out}}
<pre>
http%3A%2F%2Ffoo+bar%2F
</pre>
=={{header|Groovy}}==
<
def normal = "http://foo bar/"
def encoded = URLEncoder.encode(normal, "utf-8")
println encoded
</syntaxhighlight>
{{out}}
<pre>
Line 452 ⟶ 772:
=={{header|Haskell}}==
<
import Text.Printf
Line 465 ⟶ 785:
main :: IO ()
main = putStrLn $ urlEncode "http://foo bar/"</
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main()
Line 488 ⟶ 808:
return c
end
</syntaxhighlight>
{{libheader|Icon Programming Library}}
Line 503 ⟶ 823:
Here's an implementation that does that:
<
urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.)</
Example use:
<
http%3A%2F%2Ffoo%20bar%2F</
=={{header|Java}}==
Java includes the ''URLEncoder'' and ''URLDecoder'' classes for this specific task.
<syntaxhighlight lang="java">
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
</syntaxhighlight>
<syntaxhighlight lang="java">
URLEncoder.encode("http://foo bar/", StandardCharsets.UTF_8)
</syntaxhighlight>
Alternately, you could implement this with a basic for-loop.
<syntaxhighlight lang="java">
String encode(String string) {
StringBuilder encoded = new StringBuilder();
for (char character : string.toCharArray()) {
switch (character) {
/* rfc3986 and html5 */
case '-', '.', '_', '~', '*' -> encoded.append(character);
case ' ' -> encoded.append('+');
default -> {
if (alphanumeric(character))
encoded.append(character);
else {
encoded.append("%");
encoded.append("%02x".formatted((int) character));
}
}
}
}
return encoded.toString();
}
boolean alphanumeric(char character) {
return (character >= 'A' && character <= 'Z')
|| (character >= 'a' && character <= 'z')
|| (character >= '0' && character <= '9');
}
</syntaxhighlight>
<pre>
http%3a%2f%2ffoo+bar%2f
</pre>
=={{header|JavaScript}}==
Confusingly, there are 3 different URI encoding functions in JavaScript: <code>escape()</code>, <code>encodeURI()</code>, and <code>encodeURIComponent()</code>. Each of them encodes a different set of characters. See [http://www.javascripter.net/faq/escape.htm this article] and [http://xkr.us/articles/javascript/encode-compare/ this article] for more information and comparisons.
<
var encoded = encodeURIComponent(normal);</
=={{header|jq}}==
Line 546 ⟶ 888:
Note that @uri also converts multibyte characters to multi-triplets, e.g.
<
<
# The helper function checks whether the input corresponds to one of the characters: !'()*
def recode: . as $c | [33,39,40,41,42] | index($c);
Line 555 ⟶ 897:
# 37 ==> "%", 50 ==> "2"
| map( if recode then (37, 50, ((. - 32) | hex)) else . end )
| implode;</
'''Examples:'''
<
produces: "http%3A%2F%2Ffoo%20bar%2F"
<
To contrast the difference between "@uri" and "url_encode", we compare the characters that are unaltered:
<
produces: "!'()*-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"
<
produces: "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"
=={{header|Julia}}==
<syntaxhighlight lang="julia">
//version 1.0.1
import HTTP.URIs: escapeuri
Line 580 ⟶ 922:
println(dcd, " => ", enc)
</syntaxhighlight>
{{out}}
Line 588 ⟶ 930:
=={{header|Kotlin}}==
<
import java.net.URLEncoder
Line 595 ⟶ 937:
val url = "http://foo bar/"
println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20
}</
{{out}}
Line 602 ⟶ 944:
</pre>
=={{header|
<syntaxhighlight lang="ksh">
url_encode()
{
}
url_encode "http://foo bar/"
url_encode "https://ru.wikipedia.org/wiki/Транспайлер"
url_encode "google.com/search?q=`Abdu'l-Bahá"
</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo%20bar%2F
https%3A%2F%2Fru.wikipedia.org%2Fwiki%2F%D0%A2%D1%80%D0%B0%D0%BD%D1%81%D0%BF%D0%B0%D0%B9%D0%BB%D0%B5%D1%80
google.com%2Fsearch%3Fq%3D%60Abdu%27l-Bah%C3%A1
</pre>
=={{header|langur}}==
<syntaxhighlight lang="langur">val .urlEncode = fn(.s) {
replace(
.s, re/[^A-Za-z0-9]/,
fn(.s2) { join "", map fn(.b) { $"%\.b:X02;" }, s2b .s2 },
)
}
writeln .urlEncode("https://some website.com/")</syntaxhighlight>
{{out}}
<pre>https
=={{header|Lasso}}==
<
-> http%3A%2F%2Ffoo%20bar%2F
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
dim lookUp$( 256)
Line 653 ⟶ 1,007:
next j
end function
</syntaxhighlight>
<pre>
Supplied string 'http://foo bar/'
Line 662 ⟶ 1,016:
Lingo implements old-school URL encoding (with spaces encoded as "+") out of the box:
<
-- "http%3a%2f%2ffoo+bar%2f"</
For RFC 3986 URL encoding (i.e. without the "+" fuss) a custom function is needed - which might call the above function and then just replace all "+" with "%20".
=={{header|LiveCode}}==
<
-- http%3A%2F%2Ffoo+bar%2F</
=={{header|Lua}}==
<
return string.format("%%%X",string.byte(chr))
end
Line 682 ⟶ 1,036:
-- will print "http%3A%2F%2Ffoo%20bar%2F"
print(encodeString("http://foo bar/"))</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Function decodeUrl$(a$) {
Line 755 ⟶ 1,109:
}
CheckIt
</syntaxhighlight>
<pre style="height:30ex;overflow:scroll">
"http%3A%2F%2Ffoo%20bar%2F"
Line 767 ⟶ 1,121:
=={{header|Maple}}==
<
{{out}}
<pre>"http%3A%2F%2Ffoo%20bar%2F"</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
StringReplace[url,
x : Except[
Line 779 ⟶ 1,133:
CharacterRange["A", "Z"]]] :>
StringJoin[("%" ~~ #) & /@
IntegerString[ToCharacterCode[x, "UTF8"], 16]]]</
Example use:
<syntaxhighlight lang="mathematica">URLEncoding["http://foo bar/"]</syntaxhighlight>
{{out}}
<pre>http%3a%2f%2ffoo%20bar%2f</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<
u = '';
for k = 1:length(s),
Line 798 ⟶ 1,149:
end;
end
end</
Usage:
<pre>octave:3> urlencoding('http://foo bar/')
Line 804 ⟶ 1,155:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 868 ⟶ 1,219:
return
</syntaxhighlight>
{{out}}
Line 903 ⟶ 1,254:
=={{header|NewLISP}}==
<
;; (source http://www.newlisp.org/index.cgi?page=Code_Snippets)
(define (url-encode str)
(replace {([^a-zA-Z0-9])} str (format "%%%2X" (char $1)) 0))
(url-encode "http://foo bar/")</
=={{header|Nim}}==
<
echo encodeUrl("http://foo/bar/")</
{{out}}
<pre>http%3A%2F%2Ffoo%2Fbar%2F</pre>
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE URLEncoding;
IMPORT
Line 930 ⟶ 1,284:
Out.String(encodedUrl.ToString());Out.Ln
END URLEncoding.
</syntaxhighlight>
{{out}}
<pre>
Line 937 ⟶ 1,291:
=={{header|Objeck}}==
<
use FastCgi;
Line 948 ⟶ 1,302:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", encoded);</
The Core Foundation function <code>CFURLCreateStringByAddingPercentEscapes()</code> provides more options.
Line 959 ⟶ 1,313:
{{works with|Mac OS X|10.9+}}
{{works with|iOS|7+}}
<
NSString *encoded = [normal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSLog(@"%@", encoded);</
For encoding for various parts of the URL, the allowed character sets <code>[NSCharacterSet URLUserAllowedCharacterSet]</code>, <code>[NSCharacterSet URLPasswordAllowedCharacterSet]</code>, <code>[NSCharacterSet URLHostAllowedCharacterSet]</code>, <code>[NSCharacterSet URLPathAllowedCharacterSet]</code>, <code>[NSCharacterSet URLQueryAllowedCharacterSet]</code>, or <code>[NSCharacterSet URLFragmentAllowedCharacterSet]</code> are provided.
Line 969 ⟶ 1,323:
Using the library [http://projects.camlcity.org/projects/ocamlnet.html ocamlnet] from the interactive loop:
<
# #use "topfind";;
# #require "netstring";;
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"</
=={{header|ooRexx}}==
Line 984 ⟶ 1,338:
=={{header|Perl}}==
<
my $s = shift;
$s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg;
Line 992 ⟶ 1,346:
print urlencode('http://foo bar/')."\n";
</syntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F
</pre>
<
my $s = 'http://foo/bar/';
print uri_escape($s);</
Use standard CGI module:
<
use CGI;
my $s = 'http://foo/bar/';
say $s = CGI::escape($s);
say $s = CGI::unescape($s);</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\encode_url.exw
-- ===========================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">nib</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">9</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">encode_url</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">exclusions</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">spaceplus</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">' '</span> <span style="color: #008080;">and</span> <span style="color: #000000;">spaceplus</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'+'</span>
<span style="color: #008080;">elsif</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">exclusions</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'0'</span>
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'9'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'Z'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'%'</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">nib</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">/</span><span style="color: #000000;">#10</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nib</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#0F</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">ch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">encode_url</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"http://foo bar/"</span><span style="color: #0000FF;">)})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 1,046 ⟶ 1,404:
=={{header|PHP}}==
<
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?></
There is also <code>urlencode()</code>, which also encodes spaces as "+" signs
=={{header|PicoLisp}}==
<
(pack
(mapcar
Line 1,060 ⟶ 1,418:
C
(list '% (hex (char C))) ) )
(chop Str) ) ) )</
Test:
<pre>: (urlEncodeTooMuch "http://foo bar/")
Line 1,066 ⟶ 1,424:
=={{header|Pike}}==
<
{{Out}}
<pre>
Line 1,073 ⟶ 1,431:
=={{header|Powershell}}==
<syntaxhighlight lang="powershell">
[uri]::EscapeDataString('http://foo bar/')
http%3A%2F%2Ffoo%20bar%2F
</syntaxhighlight>
=={{header|PureBasic}}==
<
=={{header|Python}}==
<
s = 'http://foo/bar/'
s = urllib.quote(s)</
There is also <code>urllib.quote_plus()</code>, which also encodes spaces as "+" signs
Line 1,092 ⟶ 1,450:
R has a built-in
<
function, but it doesn't fully follow RFC guidelines, so we have to use another R package to accomplish the task:
<syntaxhighlight lang="r">
library(RCurl)
curlEscape("http://foo bar/")
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
(require net/uri-codec)
(uri-encode "http://foo bar/")
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say $url.subst(/<-alnum>/, *.ord.fmt("%%%02X"), :g);</
{{out}}
Line 1,120 ⟶ 1,478:
=={{header|REALbasic}}==
Using the built-in encoding method, which doesn't permit exceptions:
<syntaxhighlight lang="vb">
Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
</syntaxhighlight>
With optional exceptions. A "ParamArray" is an array of zero or more additional arguments passed by the caller:
<syntaxhighlight lang="vb">
Function URLEncode(Data As String, ParamArray Exceptions() As String) As String
Dim buf As String
Line 1,149 ⟶ 1,507:
Dim s As String = URLEncode("http://foo bar/") ' no exceptions
Dim t As String = URLEncode("http://foo bar/", "!", "?", ",") ' with exceptions
</syntaxhighlight>
=={{header|REXX}}==
===version 1===
<
do
call testcase
Line 1,225 ⟶ 1,583:
return
end
</syntaxhighlight>
{{out}}
Line 1,260 ⟶ 1,618:
===version 2===
<
url.=; url.1= 'http://foo bar/'
url.2= 'mailto:"Ivan Aim" <ivan.aim@email.com>'
Line 1,287 ⟶ 1,645:
end /*select*/
end /*k*/
return z</
'''output''' when using the default input:
<pre>
Line 1,306 ⟶ 1,664:
<code>CGI.escape</code> encodes all characters except '-.0-9A-Z_a-z'.
<
puts CGI.escape("http://foo bar/").gsub("+", "%20")
# => "http%3A%2F%2Ffoo%20bar%2F"</
Programs should not call <code>URI.escape</code> (alias <code>URI.encode</code>), because it fails to encode some characters. <code>URI.escape</code> is [http://www.ruby-forum.com/topic/207489 obsolete] since Ruby 1.9.2.
Line 1,315 ⟶ 1,673:
{{works with|Ruby|1.9.2}}
<
puts URI.encode_www_form_component("http://foo bar/").gsub("+", "%20")
# => "http%3A%2F%2Ffoo%20bar%2F"</
=={{header|Run BASIC}}==
<
for i = 1 to len(urlIn$)
Line 1,328 ⟶ 1,686:
or (a$ >= "a" and a$ <= "z") then url$ = url$ + a$ else url$ = url$ + "%"+dechex$(asc(a$))
next i
print urlIn$;" -> ";url$</
<pre>http://foo bar/ -> http%3A%2F%2Ffoo%20bar%2F</pre>
=={{header|Rust}}==
<
const MAX_CHAR_VAL: u32 = std::char::MAX as u32;
Line 1,349 ⟶ 1,707:
.collect::<String>()
);
}</
{{Out}}
<pre>
Line 1,356 ⟶ 1,714:
=={{header|Scala}}==
{{libheader|Scala}}<
import scala.compat.Platform.currentTime
Line 1,371 ⟶ 1,729:
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</
=={{header|Seed7}}==
Line 1,381 ⟶ 1,739:
works like ''toPercentEncoded'' and additionally encodes a space with '+'.
Both functions work for byte sequences (characters beyond '\255\' raise the exception RANGE_ERROR).
To encode Unicode characters it is necessary to convert them to UTF-8 with
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "encoding.s7i";
Line 1,388 ⟶ 1,747:
writeln(toPercentEncoded("http://foo bar/"));
writeln(toUrlEncoded("http://foo bar/"));
end func;</
{{out}}
http%3A%2F%2Ffoo%20bar%2F
http%3A%2F%2Ffoo+bar%2F
Line 1,394 ⟶ 1,754:
=={{header|Sidef}}==
{{trans|Perl}}
<
str.gsub!(%r"([^-A-Za-z0-9_.!~*'() ])", {|a| "%%%02X" % a.ord});
str.gsub!(' ', '+');
Line 1,400 ⟶ 1,760:
}
say urlencode('http://foo bar/');</
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
=={{header|Tcl}}==
<
# See http://tools.ietf.org/html/rfc3986 §2.4 and §2.5
proc urlEncode {str} {
Line 1,412 ⟶ 1,772:
set replacement {%[format "%02X" [scan "\\\0" "%c"]]}
return [string map {"\n" "%0A"} [subst [regsub -all $chRE $uStr $replacement]]]
}</
Demonstrating:
<
{{out}}
<pre>http%3A%2F%2Ffoo%20bar%2F%E2%82%AC</pre>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
text="http://foo bar/"
Line 1,430 ⟶ 1,790:
print "text: ", text
PRINT "encoded: ", url_encoded
</syntaxhighlight>
{{out}}
<pre>
Line 1,441 ⟶ 1,801:
{{works with|bash}}
unfortunately ksh does not support <code>"'$c"</code> syntax
<
{
typeset decoded=$1 encoded= rest= c=
Line 1,488 ⟶ 1,848:
fi
}
</syntaxhighlight>
=={{header|VBScript}}==
<
For i = 1 To Len(url)
n = Asc(Mid(url,i,1))
Line 1,506 ⟶ 1,866:
End Function
WScript.Echo UrlEncode("http://foo baré/")</
{{out}}
<pre>http%3A%2F%2Ffoo%20bar%C3%A9%2F</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import net.urllib
fn main() {
println(urllib.query_escape("http://foo bar/"))
}</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo+bar%2F
</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
var urlEncode = Fn.new { |url|
var res = ""
for (b in url.bytes) {
if ((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {
res = res + String.fromByte(b)
} else {
res = res + Fmt.swrite("\%$2X", b)
}
}
return res
}
var urls = [
"http://foo bar/",
"mailto:\"Ivan Aim\" <ivan.aim@email.com>",
"mailto:\"Irma User\" <irma.user@mail.com>",
"http://foo.bar.com/~user-name/_subdir/*~.html"
]
for (url in urls) System.print(urlEncode.call(url))</syntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo%20bar%2F
mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E
mailto%3A%22Irma%20User%22%20%3Cirma%2Euser%40mail%2Ecom%3E
http%3A%2F%2Ffoo%2Ebar%2Ecom%2F%7Euser%2Dname%2F%5Fsubdir%2F%2A%7E%2Ehtml
</pre>
=={{header|XPL0}}==
<
string 0; \use zero-terminated strings
Line 1,532 ⟶ 1,934:
];
Text(0, Encode("http://foo bar/"))</
{{out}}
Line 1,541 ⟶ 1,943:
=={{header|Yabasic}}==
{{trans|Phix}}
<
local res$, i, ch$
Line 1,557 ⟶ 1,959:
end sub
print encode_url$("http://foo bar/")</
=={{header|zkl}}==
Using lib cURL:
<
CURL.urlEncode("http://foo bar/") //--> "http%3A%2F%2Ffoo%20bar%2F"</
|