URL encoding: Difference between revisions
→{{header|langur}}
m (→{{header|Phix}}: syntax coloured) |
Langurmonkey (talk | contribs) |
||
(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:
** 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}}==
<
V r = ‘’
V buf = ‘’
Line 63 ⟶ 65:
print(url_encode(‘http://foo bar/’))
print(url_encode(‘https://ru.wikipedia.org/wiki/Транспайлер’))</
{{out}}
Line 72 ⟶ 74:
=={{header|Action!}}==
<
BYTE i
Line 160 ⟶ 162:
Test("http://www.rosettacode.org/wiki/URL_encoding")
Test("http://foo bar/*_-.html")
RETURN</
{{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}}
<
with Ada.Text_IO; use Ada.Text_IO;
procedure Encode is
Line 188 ⟶ 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 226 ⟶ 228:
print( ( encode url( "http://foo bar/" ), newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
Line 233 ⟶ 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</
{{out}}
Line 252 ⟶ 270:
=={{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 296 ⟶ 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 315 ⟶ 355:
ENDIF
ENDWHILE
= url$</
{{out}}
<pre>
Line 322 ⟶ 362:
=={{header|Bracmat}}==
<
= encoded exceptions octet string
. !arg:(?exceptions.?string)
Line 363 ⟶ 403:
& out$(encode$("-._~"."http://foo.bar.com/~user-name/_subdir/*~.html"))
);
</syntaxhighlight>
{{out}}
<pre>without exceptions:
Line 384 ⟶ 424:
=={{header|C}}==
<
#include <ctype.h>
Line 417 ⟶ 457:
return 0;
}</
=={{header|C sharp}}==
<
namespace URLEncode
Line 437 ⟶ 477:
}
}
}</
{{out}}
Line 445 ⟶ 485:
=={{header|C++}}==
using Qt 4.6 as a library
<
#include <iostream>
Line 453 ⟶ 493:
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}</
{{out}}
<PRE>http%3A%2F%2Ffoo%20bar%2F</PRE>
Line 459 ⟶ 499:
=={{header|Clojure}}==
Using Java's URLEncoder:
<
(URLEncoder/encode "http://foo bar/" "UTF-8")</
{{out}}<pre>"http%3A%2F%2Ffoo+bar%2F"</pre>
Line 467 ⟶ 507:
=={{header|Common Lisp}}==
<
(not (digit-char-p char 36)))
Line 481 ⟶ 521:
url)))
(url-encode "http://foo bar/")</
{{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.
<
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)</
{{out}}
<pre>http://foo%20bar/
Line 500 ⟶ 540:
=={{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 539 ⟶ 629:
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
let main args =
printfn "%s" (Uri.EscapeDataString(args.[0]))
0</
{{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.
<
: my-url-encode ( str -- encoded )
[ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;
"http://foo bar/" my-url-encode print</
{{out}}
<pre>
Line 564 ⟶ 654:
=={{header|Free Pascal}}==
<
var
ch: AnsiChar;
Line 575 ⟶ 665:
Result := Result + ch;
end;
end;</
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<
Dim Shared As String lookUp(256)
For cadena As Integer = 0 To 256
Line 604 ⟶ 694:
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 620 ⟶ 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 638 ⟶ 772:
=={{header|Haskell}}==
<
import Text.Printf
Line 651 ⟶ 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 674 ⟶ 808:
return c
end
</syntaxhighlight>
{{libheader|Icon Programming Library}}
Line 689 ⟶ 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 732 ⟶ 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 741 ⟶ 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 766 ⟶ 922:
println(dcd, " => ", enc)
</syntaxhighlight>
{{out}}
Line 774 ⟶ 930:
=={{header|Kotlin}}==
<
import java.net.URLEncoder
Line 781 ⟶ 937:
val url = "http://foo bar/"
println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20
}</
{{out}}
Line 789 ⟶ 945:
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
url_encode()
{
Line 799 ⟶ 955:
url_encode "https://ru.wikipedia.org/wiki/Транспайлер"
url_encode "google.com/search?q=`Abdu'l-Bahá"
</syntaxhighlight>
{{out}}
Line 810 ⟶ 966:
=={{header|langur}}==
<syntaxhighlight lang="langur">val .urlEncode = fn(.s) {
.s, re/[^A-Za-z0-9]/,
)
}
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 860 ⟶ 1,007:
next j
end function
</syntaxhighlight>
<pre>
Supplied string 'http://foo bar/'
Line 869 ⟶ 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 889 ⟶ 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 962 ⟶ 1,109:
}
CheckIt
</syntaxhighlight>
<pre style="height:30ex;overflow:scroll">
"http%3A%2F%2Ffoo%20bar%2F"
Line 974 ⟶ 1,121:
=={{header|Maple}}==
<
{{out}}
Line 980 ⟶ 1,127:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
StringReplace[url,
x : Except[
Line 986 ⟶ 1,133:
CharacterRange["A", "Z"]]] :>
StringJoin[("%" ~~ #) & /@
IntegerString[ToCharacterCode[x, "UTF8"], 16]]]</
Example use:
<
{{out}}
<pre>http%3a%2f%2ffoo%20bar%2f</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<
u = '';
for k = 1:length(s),
Line 1,002 ⟶ 1,149:
end;
end
end</
Usage:
<pre>octave:3> urlencoding('http://foo bar/')
Line 1,008 ⟶ 1,155:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,072 ⟶ 1,219:
return
</syntaxhighlight>
{{out}}
Line 1,107 ⟶ 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}}
Line 1,124 ⟶ 1,271:
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE URLEncoding;
IMPORT
Line 1,137 ⟶ 1,284:
Out.String(encodedUrl.ToString());Out.Ln
END URLEncoding.
</syntaxhighlight>
{{out}}
<pre>
Line 1,144 ⟶ 1,291:
=={{header|Objeck}}==
<
use FastCgi;
Line 1,155 ⟶ 1,302:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", encoded);</
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+}}
<
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 1,176 ⟶ 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 1,191 ⟶ 1,338:
=={{header|Perl}}==
<
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>
{{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}}==
<!--<
<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>
<!--</
{{Out}}
<pre>
Line 1,257 ⟶ 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,271 ⟶ 1,418:
C
(list '% (hex (char C))) ) )
(chop Str) ) ) )</
Test:
<pre>: (urlEncodeTooMuch "http://foo bar/")
Line 1,277 ⟶ 1,424:
=={{header|Pike}}==
<
{{Out}}
<pre>
Line 1,284 ⟶ 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,303 ⟶ 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,331 ⟶ 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,360 ⟶ 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,436 ⟶ 1,583:
return
end
</syntaxhighlight>
{{out}}
Line 1,471 ⟶ 1,618:
===version 2===
<
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</
'''output''' when using the default input:
<pre>
Line 1,517 ⟶ 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,526 ⟶ 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,539 ⟶ 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,560 ⟶ 1,707:
.collect::<String>()
);
}</
{{Out}}
<pre>
Line 1,567 ⟶ 1,714:
=={{header|Scala}}==
{{libheader|Scala}}<
import scala.compat.Platform.currentTime
Line 1,582 ⟶ 1,729:
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</
=={{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
<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;</
{{out}}
http%3A%2F%2Ffoo%20bar%2F
http%3A%2F%2Ffoo+bar%2F
Line 1,605 ⟶ 1,754:
=={{header|Sidef}}==
{{trans|Perl}}
<
str.gsub!(%r"([^-A-Za-z0-9_.!~*'() ])", {|a| "%%%02X" % a.ord});
str.gsub!(' ', '+');
Line 1,611 ⟶ 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,623 ⟶ 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,641 ⟶ 1,790:
print "text: ", text
PRINT "encoded: ", url_encoded
</syntaxhighlight>
{{out}}
<pre>
Line 1,652 ⟶ 1,801:
{{works with|bash}}
unfortunately ksh does not support <code>"'$c"</code> syntax
<
{
typeset decoded=$1 encoded= rest= c=
Line 1,699 ⟶ 1,848:
fi
}
</syntaxhighlight>
=={{header|VBScript}}==
<
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é/")</
{{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}}
<
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))</
{{out}}
Line 1,755 ⟶ 1,914:
=={{header|XPL0}}==
<
string 0; \use zero-terminated strings
Line 1,775 ⟶ 1,934:
];
Text(0, Encode("http://foo bar/"))</
{{out}}
Line 1,784 ⟶ 1,943:
=={{header|Yabasic}}==
{{trans|Phix}}
<
local res$, i, ch$
Line 1,800 ⟶ 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"</
|