URL encoding: Difference between revisions

7,291 bytes added ,  14 days ago
m (→‎{{header|Phix}}: syntax coloured)
 
(24 intermediate revisions by 13 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:
* Some standards give different rules: RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says that "-._~" should not be encoded. 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 "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific 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 41 ⟶ 43:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F url_encode(s)
V r = ‘’
V buf = ‘’
Line 63 ⟶ 65:
 
print(url_encode(‘http://foo bar/’))
print(url_encode(‘https://ru.wikipedia.org/wiki/Транспайлер’))</langsyntaxhighlight>
 
{{out}}
Line 72 ⟶ 74:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC MustEncode(CHAR c CHAR ARRAY ex)
BYTE i
 
Line 160 ⟶ 162:
Test("http://www.rosettacode.org/wiki/URL_encoding")
Test("http://foo bar/*_-.html")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/URL_encoding.png Screenshot from Atari 8-bit computer]
Line 182 ⟶ 184:
=={{header|Ada}}==
{{libheader|AWS}}
<langsyntaxhighlight Adalang="ada">with AWS.URL;
with Ada.Text_IO; use Ada.Text_IO;
procedure Encode is
Line 188 ⟶ 190:
begin
Put_Line (AWS.URL.Encode (Normal));
end Encode;</langsyntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo%20bar%2F</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# 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 226 ⟶ 228:
print( ( encode url( "http://foo bar/" ), newline ) )
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 233 ⟶ 235:
 
=={{header|Apex}}==
<langsyntaxhighlight lang="apex">EncodingUtil.urlEncode('http://foo bar/', 'UTF-8')</langsyntaxhighlight>
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
 
=={{header|AppleScript}}==
{{libheader|AppleScript Toolbox}}
<langsyntaxhighlight AppleScriptlang="applescript">AST URL encode "http://foo bar/"</langsyntaxhighlight>
{{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}}==
 
<langsyntaxhighlight lang="rebol">encoded: encode.url.slashes "http://foo bar/"
print encoded</langsyntaxhighlight>
 
{{out}}
Line 252 ⟶ 270:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, % UriEncode("http://foo bar/")
 
; 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")) {
f := A_FormatInteger
If InStr(Unreserved . Reserved, Chr(Code)) {
SetFormat, IntegerFast, H
Encoded .= Chr(Code)
While Code := NumGet(Var, A_Index - 1, "UChar")
}
If (Code >= 0x30 && Code <= 0x39 ; 0-9
Else {
|| Code >= 0x41 && Code <= 0x5A ; A-Z
||Encoded Code >.= 0x61 &&Format("%{:02X}", Code <= 0x7A) ; a-z
}
Res .= Chr(Code)
}
Else
Return Encoded
Res .= "%" . SubStr(Code + 0x100, -1)
}</syntaxhighlight>
SetFormat, IntegerFast, %f%
Return, Res
}</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
for (i = 0; i <= 255; i++)
ord[sprintf("%c", i)] = i
Line 296 ⟶ 312:
 
# Escape every line of input.
{ print escape($0) }</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="bbcbasic"> PRINT FNurlencode("http://foo bar/")
END
Line 315 ⟶ 355:
ENDIF
ENDWHILE
= url$</langsyntaxhighlight>
{{out}}
<pre>
Line 322 ⟶ 362:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( encode
= encoded exceptions octet string
. !arg:(?exceptions.?string)
Line 363 ⟶ 403:
& out$(encode$("-._~"."http://foo.bar.com/~user-name/_subdir/*~.html"))
);
</syntaxhighlight>
</lang>
{{out}}
<pre>without exceptions:
Line 384 ⟶ 424:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <ctype.h>
Line 417 ⟶ 457:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
 
<langsyntaxhighlight lang="c sharp">using System;
 
namespace URLEncode
Line 437 ⟶ 477:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 445 ⟶ 485:
=={{header|C++}}==
using Qt 4.6 as a library
<langsyntaxhighlight lang="cpp">#include <QByteArray>
#include <iostream>
 
Line 453 ⟶ 493:
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<PRE>http%3A%2F%2Ffoo%20bar%2F</PRE>
Line 459 ⟶ 499:
=={{header|Clojure}}==
Using Java's URLEncoder:
<langsyntaxhighlight lang="clojure">(import 'java.net.URLEncoder)
(URLEncoder/encode "http://foo bar/" "UTF-8")</langsyntaxhighlight>
 
{{out}}<pre>"http%3A%2F%2Ffoo+bar%2F"</pre>
Line 467 ⟶ 507:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun needs-encoding-p (char)
(not (digit-char-p char 36)))
 
Line 481 ⟶ 521:
url)))
 
(url-encode "http://foo bar/")</langsyntaxhighlight>
{{out}}
<pre>"http%3A%2F%2Ffoo%20bar%2F"</pre>
Line 487 ⟶ 527:
=={{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.
<langsyntaxhighlight 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)</langsyntaxhighlight>
{{out}}
<pre>http://foo%20bar/
Line 500 ⟶ 540:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.uri;
 
void main() {
writeln(encodeComponent("http://foo bar/"));
}</langsyntaxhighlight>
<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}}==
<langsyntaxhighlight lang="elixir">iex(1)> URI.encode("http://foo bar/", &URI.char_unreserved?/1)
"http%3A%2F%2Ffoo%20bar%2F"</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 539 ⟶ 629:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
[<EntryPoint>]
let main args =
printfn "%s" (Uri.EscapeDataString(args.[0]))
0</langsyntaxhighlight>
{{out}}
<pre>>URLencoding.exe "http://foo bar/"
Line 551 ⟶ 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.
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit unicode urls.encoding.private ;
 
: my-url-encode ( str -- encoded )
[ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;
 
"http://foo bar/" my-url-encode print</langsyntaxhighlight>
{{out}}
<pre>
Line 564 ⟶ 654:
=={{header|Free Pascal}}==
 
<langsyntaxhighlight lang="pascal">function urlEncode(data: string): AnsiString;
var
ch: AnsiChar;
Line 575 ⟶ 665:
Result := Result + ch;
end;
end;</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang="freebasic">
Dim Shared As String lookUp(256)
For cadena As Integer = 0 To 256
Line 604 ⟶ 694:
Print "URL encoding '"; string2url(URL); "'"
Sleep
</syntaxhighlight>
</lang>
{{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}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 620 ⟶ 753:
func main() {
fmt.Println(url.QueryEscape("http://foo bar/"))
}</langsyntaxhighlight>
{{out}}
<pre>
http%3A%2F%2Ffoo+bar%2F
</pre>
 
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">
def normal = "http://foo bar/"
def encoded = URLEncoder.encode(normal, "utf-8")
println encoded
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 638 ⟶ 772:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import qualified Data.Char as Char
import Text.Printf
 
Line 651 ⟶ 785:
 
main :: IO ()
main = putStrLn $ urlEncode "http://foo bar/"</langsyntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link hexcvt
 
procedure main()
Line 674 ⟶ 808:
return c
end
</syntaxhighlight>
</lang>
 
{{libheader|Icon Programming Library}}
Line 689 ⟶ 823:
Here's an implementation that does that:
 
<langsyntaxhighlight lang="j">require'strings convert'
urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> urlencode 'http://foo bar/'
http%3A%2F%2Ffoo%20bar%2F</langsyntaxhighlight>
 
=={{header|Java}}==
Java includes the ''URLEncoder'' and ''URLDecoder'' classes for this specific task.
 
<syntaxhighlight lang="java">
The built-in URLEncoder in Java converts the space " " into a plus-sign "+" instead of "%20":
<lang java>import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
</syntaxhighlight>
public class Main
<syntaxhighlight lang="java">
{
URLEncoder.encode("http://foo bar/", StandardCharsets.UTF_8)
public static void main(String[] args) throws UnsupportedEncodingException
</syntaxhighlight>
{
Alternately, you could implement this with a basic for-loop.
String normal = "http://foo bar/";
<syntaxhighlight lang="java">
String encoded = URLEncoder.encode(normal, "utf-8");
String encode(String string) {
System.out.println(encoded);
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();
}</lang>
}
 
boolean alphanumeric(char character) {
{{out}}
return (character >= 'A' && character <= 'Z')
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
|| (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.
<langsyntaxhighlight lang="javascript">var normal = 'http://foo/bar/';
var encoded = encodeURIComponent(normal);</langsyntaxhighlight>
 
=={{header|jq}}==
Line 732 ⟶ 888:
 
Note that @uri also converts multibyte characters to multi-triplets, e.g.
<langsyntaxhighlight lang="jq">"á" | @uri</langsyntaxhighlight> produces: "%C3%A1"
<langsyntaxhighlight lang="jq">def url_encode:
# 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 741 ⟶ 897:
# 37 ==> "%", 50 ==> "2"
| map( if recode then (37, 50, ((. - 32) | hex)) else . end )
| implode;</langsyntaxhighlight>
'''Examples:'''
 
<langsyntaxhighlight lang="jq">"http://foo bar/" | @uri</langsyntaxhighlight>
produces: "http%3A%2F%2Ffoo%20bar%2F"
 
<langsyntaxhighlight lang="jq">"http://foo bar/" | @uri == url_encode</langsyntaxhighlight> produces: true
 
To contrast the difference between "@uri" and "url_encode", we compare the characters that are unaltered:
 
<langsyntaxhighlight lang="jq">[range(0;1024) | [.] | implode | if @uri == . then . else empty end] | join(null)</langsyntaxhighlight>
produces: "!'()*-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"
 
<langsyntaxhighlight lang="jq">[range(0;1024) | [.] | implode | if url_encode == . then . else empty end] | join(null)</langsyntaxhighlight>
produces: "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
//version 1.0.1
import HTTP.URIs: escapeuri
Line 766 ⟶ 922:
 
println(dcd, " => ", enc)
</syntaxhighlight>
</lang>
 
{{out}}
Line 774 ⟶ 930:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.net.URLEncoder
Line 781 ⟶ 937:
val url = "http://foo bar/"
println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20
}</langsyntaxhighlight>
 
{{out}}
Line 789 ⟶ 945:
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
<lang Ksh>
url_encode()
{
Line 799 ⟶ 955:
url_encode "https://ru.wikipedia.org/wiki/Транспайлер"
url_encode "google.com/search?q=`Abdu'l-Bahá"
</syntaxhighlight>
</lang>
 
{{out}}
Line 810 ⟶ 966:
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .urlEncode = fn(.s) {
{{works with|langur|0.9.6}}
<lang langur>val .urlEncode = f(.s) replace(
.s, re/[^A-Za-z0-9]/,
ffn(.s2) for{ .bjoin in"", s2b(.s2)map {fn _for.b: ~= $"%\{{.b:X02;}}", s2b .s2 },
)
)
}
 
val .original = "https://some website.com/"
 
writeln .original
writeln .urlEncode(.original)</lang>
 
This should work with non-ASCII characters as well (assuming that's valid).
 
We pass a custom anonymous function to replace(), which uses the the s2b() function (returning UTF-8 bytes from a string), and a for loop adding them all.
 
writeln .urlEncode("https://some website.com/")</syntaxhighlight>
The :X02 is an interpolation modifier, generating a hexadecimal code of at least 2 characters, padded with zeroes.
 
{{out}}
<pre>https://some website.com%3A%2F%2Fsome%20website%2Ecom%2F</pre>
https%3A%2F%2Fsome%20website%2Ecom%2F</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">bytes('http://foo bar/') -> encodeurl</langsyntaxhighlight>
-> http%3A%2F%2Ffoo%20bar%2F
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim lookUp$( 256)
 
Line 860 ⟶ 1,007:
next j
end function
</syntaxhighlight>
</lang>
<pre>
Supplied string 'http://foo bar/'
Line 869 ⟶ 1,016:
Lingo implements old-school URL encoding (with spaces encoded as "+") out of the box:
 
<langsyntaxhighlight lang="lingo">put urlencode("http://foo bar/")
-- "http%3a%2f%2ffoo+bar%2f"</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight LiveCodelang="livecode">urlEncode("http://foo bar/")
-- http%3A%2F%2Ffoo+bar%2F</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function encodeChar(chr)
return string.format("%%%X",string.byte(chr))
end
Line 889 ⟶ 1,036:
 
-- will print "http%3A%2F%2Ffoo%20bar%2F"
print(encodeString("http://foo bar/"))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function decodeUrl$(a$) {
Line 962 ⟶ 1,109:
}
CheckIt
</syntaxhighlight>
</lang>
<pre style="height:30ex;overflow:scroll">
"http%3A%2F%2Ffoo%20bar%2F"
Line 974 ⟶ 1,121:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">URL:-Escape("http://foo bar/");</langsyntaxhighlight>
 
{{out}}
Line 980 ⟶ 1,127:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">URLEncoding[url_] :=
StringReplace[url,
x : Except[
Line 986 ⟶ 1,133:
CharacterRange["A", "Z"]]] :>
StringJoin[("%" ~~ #) & /@
IntegerString[ToCharacterCode[x, "UTF8"], 16]]]</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="mathematica">URLEncoding["http://foo bar/"]</langsyntaxhighlight>
{{out}}
<pre>http%3a%2f%2ffoo%20bar%2f</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function u = urlencoding(s)
u = '';
for k = 1:length(s),
Line 1,002 ⟶ 1,149:
end;
end
end</langsyntaxhighlight>
Usage:
<pre>octave:3> urlencoding('http://foo bar/')
Line 1,008 ⟶ 1,155:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,072 ⟶ 1,219:
 
return
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,107 ⟶ 1,254:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">;; simple encoder
;; (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/")</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import cgi
 
echo encodeUrl("http://foo/bar/")</langsyntaxhighlight>
 
{{out}}
Line 1,124 ⟶ 1,271:
=={{header|Oberon-2}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE URLEncoding;
IMPORT
Line 1,137 ⟶ 1,284:
Out.String(encodedUrl.ToString());Out.Ln
END URLEncoding.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,144 ⟶ 1,291:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use FastCgi;
 
Line 1,155 ⟶ 1,302:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">NSString *normal = @"http://foo bar/";
NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", encoded);</langsyntaxhighlight>
 
The Core Foundation function <code>CFURLCreateStringByAddingPercentEscapes()</code> provides more options.
Line 1,166 ⟶ 1,313:
{{works with|Mac OS X|10.9+}}
{{works with|iOS|7+}}
<langsyntaxhighlight lang="objc">NSString *normal = @"http://foo bar/";
NSString *encoded = [normal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSLog(@"%@", encoded);</langsyntaxhighlight>
 
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 1,176 ⟶ 1,323:
Using the library [http://projects.camlcity.org/projects/ocamlnet.html ocamlnet] from the interactive loop:
 
<langsyntaxhighlight lang="ocaml">$ ocaml
# #use "topfind";;
# #require "netstring";;
 
# Netencoding.Url.encode "http://foo bar/" ;;
- : string = "http%3A%2F%2Ffoo+bar%2F"</langsyntaxhighlight>
 
=={{header|ooRexx}}==
Line 1,191 ⟶ 1,338:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">sub urlencode {
my $s = shift;
$s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg;
Line 1,199 ⟶ 1,346:
 
print urlencode('http://foo bar/')."\n";
</syntaxhighlight>
</lang>
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F
</pre>
 
<langsyntaxhighlight lang="perl">use URI::Escape;
 
my $s = 'http://foo/bar/';
print uri_escape($s);</langsyntaxhighlight>
 
Use standard CGI module:
<langsyntaxhighlight lang="perl">use 5.10.0;
use CGI;
 
my $s = 'http://foo/bar/';
say $s = CGI::escape($s);
say $s = CGI::unescape($s);</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\encode_url.exw
Line 1,250 ⟶ 1,397:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 1,257 ⟶ 1,404:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?></langsyntaxhighlight>
There is also <code>urlencode()</code>, which also encodes spaces as "+" signs
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de urlEncodeTooMuch (Str)
(pack
(mapcar
Line 1,271 ⟶ 1,418:
C
(list '% (hex (char C))) ) )
(chop Str) ) ) )</langsyntaxhighlight>
Test:
<pre>: (urlEncodeTooMuch "http://foo bar/")
Line 1,277 ⟶ 1,424:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">Protocols.HTTP.uri_encode( "http://foo bar/" );</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,284 ⟶ 1,431:
 
=={{header|Powershell}}==
<syntaxhighlight lang="powershell">
<lang Powershell>
[uri]::EscapeDataString('http://foo bar/')
 
http%3A%2F%2Ffoo%20bar%2F
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">URL$ = URLEncoder("http://foo bar/")</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import urllib
s = 'http://foo/bar/'
s = urllib.quote(s)</langsyntaxhighlight>
There is also <code>urllib.quote_plus()</code>, which also encodes spaces as "+" signs
 
Line 1,303 ⟶ 1,450:
R has a built-in
 
<langsyntaxhighlight Rlang="r">URLencode("http://foo bar/")</langsyntaxhighlight>
 
function, but it doesn't fully follow RFC guidelines, so we have to use another R package to accomplish the task:
 
<syntaxhighlight lang="r">
<lang R>
library(RCurl)
curlEscape("http://foo bar/")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require net/uri-codec)
(uri-encode "http://foo bar/")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>my $url = 'http://foo bar/';
 
say $url.subst(/<-alnum>/, *.ord.fmt("%%%02X"), :g);</langsyntaxhighlight>
 
{{out}}
Line 1,331 ⟶ 1,478:
=={{header|REALbasic}}==
Using the built-in encoding method, which doesn't permit exceptions:
<syntaxhighlight lang="vb">
<lang vb>
Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
</syntaxhighlight>
</lang>
 
With optional exceptions. A "ParamArray" is an array of zero or more additional arguments passed by the caller:
<syntaxhighlight lang="vb">
<lang vb>
Function URLEncode(Data As String, ParamArray Exceptions() As String) As String
Dim buf As String
Line 1,360 ⟶ 1,507:
Dim s As String = URLEncode("http://foo bar/") ' no exceptions
Dim t As String = URLEncode("http://foo bar/", "!", "?", ",") ' with exceptions
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight REXXlang="rexx">/* Rexx */
do
call testcase
Line 1,436 ⟶ 1,583:
return
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,471 ⟶ 1,618:
 
===version 2===
<langsyntaxhighlight lang="rexx">/*REXX program encodes a URL text, blanks ──► +, preserves -._* and -._~ */
url.=; url.1= 'http://foo bar/'
url.2= 'mailto:"Ivan Aim" <ivan.aim@email.com>'
Line 1,498 ⟶ 1,645:
end /*select*/
end /*k*/
return z</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 1,517 ⟶ 1,664:
<code>CGI.escape</code> encodes all characters except '-.0-9A-Z_a-z'.
 
<langsyntaxhighlight lang="ruby">require 'cgi'
puts CGI.escape("http://foo bar/").gsub("+", "%20")
# => "http%3A%2F%2Ffoo%20bar%2F"</langsyntaxhighlight>
 
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,526 ⟶ 1,673:
 
{{works with|Ruby|1.9.2}}
<langsyntaxhighlight lang="ruby">require 'uri'
puts URI.encode_www_form_component("http://foo bar/").gsub("+", "%20")
# => "http%3A%2F%2Ffoo%20bar%2F"</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">urlIn$ = "http://foo bar/"
 
for i = 1 to len(urlIn$)
Line 1,539 ⟶ 1,686:
or (a$ >= "a" and a$ <= "z") then url$ = url$ + a$ else url$ = url$ + "%"+dechex$(asc(a$))
next i
print urlIn$;" -> ";url$</langsyntaxhighlight>
<pre>http://foo bar/ -> http%3A%2F%2Ffoo%20bar%2F</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">const INPUT: &str = "http://foo bar/";
const MAX_CHAR_VAL: u32 = std::char::MAX as u32;
Line 1,560 ⟶ 1,707:
.collect::<String>()
);
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,567 ⟶ 1,714:
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">import java.net.{URLDecoder, URLEncoder}
import scala.compat.Platform.currentTime
 
Line 1,582 ⟶ 1,729:
 
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,592 ⟶ 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 ''striToUtf8'' before[https://seed7.<langsourceforge.net/libraries/unicode.htm#toUtf8(in_string) seed7>$toUtf8] include "seed7_05before.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "encoding.s7i";
 
Line 1,599 ⟶ 1,747:
writeln(toPercentEncoded("http://foo bar/"));
writeln(toUrlEncoded("http://foo bar/"));
end func;</langsyntaxhighlight>{{out}}
{{out}}
http%3A%2F%2Ffoo%20bar%2F
http%3A%2F%2Ffoo+bar%2F
Line 1,605 ⟶ 1,754:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func urlencode(str) {
str.gsub!(%r"([^-A-Za-z0-9_.!~*'() ])", {|a| "%%%02X" % a.ord});
str.gsub!(' ', '+');
Line 1,611 ⟶ 1,760:
}
 
say urlencode('http://foo bar/');</langsyntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo+bar%2F</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Encode all except "unreserved" characters; use UTF-8 for extended chars.
# See http://tools.ietf.org/html/rfc3986 §2.4 and §2.5
proc urlEncode {str} {
Line 1,623 ⟶ 1,772:
set replacement {%[format "%02X" [scan "\\\0" "%c"]]}
return [string map {"\n" "%0A"} [subst [regsub -all $chRE $uStr $replacement]]]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts [urlEncode "http://foo bar/"]</langsyntaxhighlight>
{{out}}
<pre>http%3A%2F%2Ffoo%20bar%2F%E2%82%AC</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
text="http://foo bar/"
Line 1,641 ⟶ 1,790:
print "text: ", text
PRINT "encoded: ", url_encoded
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,652 ⟶ 1,801:
{{works with|bash}}
unfortunately ksh does not support <code>"'$c"</code> syntax
<langsyntaxhighlight lang="bash">function urlencode
{
typeset decoded=$1 encoded= rest= c=
Line 1,699 ⟶ 1,848:
fi
}
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
<langsyntaxhighlight VBScriptlang="vbscript">Function UrlEncode(url)
For i = 1 To Len(url)
n = Asc(Mid(url,i,1))
Line 1,717 ⟶ 1,866:
End Function
 
WScript.Echo UrlEncode("http://foo baré/")</langsyntaxhighlight>
 
{{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}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var urlEncode = Fn.new { |url|
Line 1,744 ⟶ 1,903:
"http://foo.bar.com/~user-name/_subdir/*~.html"
]
for (url in urls) System.print(urlEncode.call(url))</langsyntaxhighlight>
 
{{out}}
Line 1,755 ⟶ 1,914:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Text=12;
string 0; \use zero-terminated strings
 
Line 1,775 ⟶ 1,934:
];
 
Text(0, Encode("http://foo bar/"))</langsyntaxhighlight>
 
{{out}}
Line 1,784 ⟶ 1,943:
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight Yabasiclang="yabasic">sub encode_url$(s$, exclusions$, spaceplus)
local res$, i, ch$
Line 1,800 ⟶ 1,959:
end sub
 
print encode_url$("http://foo bar/")</langsyntaxhighlight>
 
=={{header|zkl}}==
Using lib cURL:
<langsyntaxhighlight lang="zkl">var CURL=Import("zklCurl");
CURL.urlEncode("http://foo bar/") //--> "http%3A%2F%2Ffoo%20bar%2F"</langsyntaxhighlight>
885

edits