- Javascript Encode Method In Javascript
- Encode URL in JavaScript?
- Encode HTML With JavaScript
- HttpUtility.JavaScriptStringEncode Method
- Encode and Decode HTML entities using pure Javascript
- How to encode a string in JavaScript?
- Using btoa() method
- Example 1
- Using the encodeURI() method
- Example 2
- Using the encodeURIComponent() method
- Example 3
Javascript Encode Method In Javascript
Decoding in Javascript can be achieved using decodeURI function. It takes encodeURIComponent (url) string so it can decode these characters. 2. unescape () function: This function takes a string as a single parameter and uses it to decode that string encoded by the escape () function.
encodeURI( complete_uri_string ) https://www.google.com/search?q=geeks%20for%20geeks encodeURIComponent( uri_string_component ) geeks%20for%20geeks escape( string ) https://www.google.com/search?q=geeks%20for%20geeks https%3A//www.google.com/search%3Fq%3Dgeeks%20for%20geeks decodeURI( complete_encoded_uri_string ) https://www.google.com/search?q=geeks for geeks decodeURIComponent( encoded_uri_string_component ) geeks for geeks unescape(string) https://www.google.com/search?q=geeks%20for%20geeks https%3A//www.google.com/search%3Fq%3Dgeeks%20for%20geeks https://www.google.com/search?q=geeks for geeks https://www.google.com/search?q=geeks for geeks
Encode URL in JavaScript?
Stick with encodeURIComponent().The function encodeURI() does not bother to encode many characters that have semantic importance in URLs (e.g. «#», «?», and «&»). escape() is deprecated, and does not bother to encode «+» characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL …
var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + myUrl; var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl); const value = encodeURIComponent(value).replace('%20','+'); const url = 'http://example.com?lang=en&key=' + value const escapedValue = encodeURIComponent(value).replace('%20','+'); const escapedFolder = encodeURIComponent('My Folder'); // no replace const url = `http://example.com/$/?myKey=$`; qs.stringify(); // gets a=1%3D2&b=Test+1 $.param() // gets a=1%3D2&b=Test+1 const queryParams = < param1: 'value1', param2: 'value2' >const queryString = new URLSearchParams(queryParams).toString() // 'param1=value1¶m2=value2' const myUrl = "http://example.com/index.html?param=1&anotherParam=2"; const myOtherUrl = new URL("http://example.com/index.html"); myOtherUrl.search = new URLSearchParams(); console.log(myOtherUrl.toString()); var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl); function urlencode(str) < str = (str + '').toString(); // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following. return encodeURIComponent(str) .replace('!', '%21') .replace('\'', '%27') .replace('(', '%28') .replace(')', '%29') .replace('*', '%2A') .replace('%20', '+'); >encodeURI() encodeURIComponent() const baseURL = 'http://example.com/index.html'; const myUrl = new URL(baseURL); myUrl.searchParams.append('param', '1'); myUrl.searchParams.append('anotherParam', '2'); const myOtherUrl = new URL(baseURL); myOtherUrl.searchParams.append('url', myUrl.href); console.log(myUrl.href); // Outputs: http://example.com/index.html?param=1&anotherParam=2 console.log(myOtherUrl.href); // Outputs: http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2 console.log(myOtherUrl.searchParams.get('url')); // Outputs: http://example.com/index.html?param=1&anotherParam=2 const params = new URLSearchParams(myOtherUrl.search); console.log(params.get('url')); // Outputs: http://example.com/index.html?param=1&anotherParam=2 function fixedEncodeURIComponent(str) < return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A"); >encodeURI("abc%20xyz 123") // wrong: "abc%2520xyz%20123" encodeURI(decodeURI("abc%20xyz 123")) // correct: "abc%20xyz%20123" console.log(encodeURIComponent('?notEncoded=&+')); // for a whole URI don't use encodeURIComponent it will transform // the / characters and the URL won't fucntion properly console.log(encodeURIComponent("http://www.random.com/specials&char.html")); // instead use encodeURI for whole URL's console.log(encodeURI("http://www.random.com/specials&char.html")); function fixedEncodeURIComponent(str) < return encodeURIComponent(str).replace(/[!'()*]/g, function(c) < return '%' + c.charCodeAt(0).toString(16); >); > Response.Headers["land"] = "login"; $(function () < var $document = $(document); $document.ajaxSuccess(function (e, response, request) < var land = response.getResponseHeader('land'); var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location); if(land) < if (land.toString() === 'login') < window.location = redrUrl; >> >); >); var url = $(location).attr('href'); //get current url //OR var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string textarea // encode string to base64 function encode() < var txt = document.getElementById("txt1").value; var result = btoa(txt); document.getElementById("txt2").value = result; >// decode base64 back to original string function decode()
function A(url) < return escape(url); >function B(url) < return encodeURI(url); >function C(url) < return encodeURIComponent(url); >function D(url) < return new URLSearchParams().toString(); > function E(url) < return encodeURIComponent(url).replace(/[!'()]/g, escape).replace(/\*/g, "%2A"); >function F(url) < return encodeURIComponent(url).replace(/[!'()*]/g, function(c) < return '%' + c.charCodeAt(0).toString(16); >); > // ---------- // TEST // ---------- var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; [A,B,C,D,E,F] .forEach(f=> console.log(`$ ?url=$`)); This snippet only presents code of choosen solutions function encodeUrl(url) < String arr[] = url.split("/"); String encodedUrl = ""; for(int i = 0; ireturn url; > function fixedEncodeURIComponent(str) < return encodeURIComponent(str).replace(/[!'()*]/g, function(c) < return '%' + c.charCodeAt(0).toString(16); >); > var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+'); function urlEncode(text) < let encoded = ''; for (let char of text) < encoded += '%' + char.charCodeAt(0).toString(16); >return encoded; >
Encode HTML With JavaScript
Encode HTML With createTextNode in JavaScript. You can use the createTextNode method to encode a given HTML. The method accepts a string as an argument that it encodes behind the scenes. Afterward, you can grab this encoded data. You can do all this with procedural programming or a function.
function htmlEncode(string) < return string.replace(/&/g, '&') .replace(//g, '>') .replace(/'/g, ''') .replace(/"/g, '"') .replace(/\//, '/'); > console.log(htmlEncode("Hello ")); "<h1>Hello <span </h1>" function encodeWithCharCode(string) < let buffer = []; for (let i = string.length-1; i>= 0; i--) < buffer.unshift(['&#', string[i].charCodeAt(), ';'].join('')); >return buffer.join(''); > console.log(encodeWithCharCode("Hello world
")); "<h1>Hello world</h1>" function encodeWithTextNode(htmlstring) < let textarea = document.createElement('textarea'); let text = document.createTextNode(htmlstring); textarea.appendChild(text); return textarea.innerHTML; >console.log(encodeWithTextNode("Hello ")); "<h1>Hello <span </h1>" <h1>Hello <span </h1>
HttpUtility.JavaScriptStringEncode Method
HttpUtility.UrlDecode Method (System.Web) Converts a string that has been encoded for transmission in a URL into a decoded string. To encode or decode values outside of a web application, use the WebUtility class.
public: static System::String ^ JavaScriptStringEncode(System::String ^ value); public static string JavaScriptStringEncode (string? value); public static string JavaScriptStringEncode (string value); static member JavaScriptStringEncode : string -> string Public Shared Function JavaScriptStringEncode (value As String) As String public: static System::String ^ JavaScriptStringEncode(System::String ^ value, bool addDoubleQuotes); public static string JavaScriptStringEncode (string? value, bool addDoubleQuotes); public static string JavaScriptStringEncode (string value, bool addDoubleQuotes); static member JavaScriptStringEncode : string * bool -> string Public Shared Function JavaScriptStringEncode (value As String, addDoubleQuotes As Boolean) As String
Encode and Decode HTML entities using pure Javascript
The previous code creates a global variable (in the window) named htmlentities. This object contains the 2 methods encode and decode. To convert a normal string to its html characters use the encode method : htmlentities.encode («Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html
(function(window) < window.htmlentities = < /** * Converts a string to its html characters completely. * * @param str String with unescaped HTML characters **/ encode : function(str) < var buf = []; for (var i=str.length-1;i>=0;i--) < buf.unshift(['&#', str[i].charCodeAt(), ';'].join('')); >return buf.join(''); >, /** * Converts an html characterSet into its original character. * * @param str htmlSet entities **/ decode : function(str) < return str.replace(/&#(\d+);/g, function(match, dec) < return String.fromCharCode(dec); >); > >; >)(window); htmlentities.encode("Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."); // Output "Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters." htmlentities.decode("Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."); // Output "Hello, this is a test stríng >< with characters that could break html. Therefore we convert it to its html characters." // Using the global default setting (defaults to `false`): he.encode('foo © bar ≠ baz . qux'); // → 'foo © bar ≠ baz 𝌆 qux' // Passing an `options` object to `encode`, to explicitly encode all symbols: he.encode('foo © bar ≠ baz . qux', < 'encodeEverything': true >); // → 'foo © bar ≠ baz 𝌆 qux' // This setting can be combined with the `useNamedReferences` option: he.encode('foo © bar ≠ baz . qux', < 'encodeEverything': true, 'useNamedReferences': true >); // → 'foo © bar ≠ baz 𝌆 qux' he.decode('foo © bar ≠ baz 𝌆 qux'); // → 'foo © bar ≠ baz . qux'
How to encode a string in JavaScript?
Encoding is the process of converting from one data format to another format. In computer science terms, encoding is the process of converting a text into a cipher text. Encoding is different from the Encryption process.
The difference between encoding and encryption is where the encoding is used to keep data usable and data confidentiality is maintained by encryption. Encoding does not use a key for encoding process whereas for encryption there should be a key for encryption process. The methods that are used to encode a string in JavaScript are btoa(), encodeURI(), encodeURIComponent().
Using btoa() method
A string in base-64 is encoded into Base64-encoded ASCII string using the btoa() function. The syntax for btoa() method is −
Where, the parameter string is the string to be encoded. The return value is an encoded string.
Example 1
This is an example program to encode a string using btoa() method.
The output for the above example program is −
Using the encodeURI() method
The encodeURI() function encodes a URI or a string by replacing each instance of certain characters like white spaces by escape sequences representing the UTF-8 encoding of the character. The syntax for encodeURI() method is
Where, the parameter uri is a complete URI or a string. The return value is an encoded string.
Example 2
This is an example program to encode a string using encodeURI() method.
The output for the above example program is −
Using the encodeURIComponent() method
The encodeURIComponent() method is an advanced version for encodeURI() method. The difference between encodeURI() and encodeURIComponent() method is where the encoding a whole URL is done using encodeURI(), but encoding a URI component, such a query string, is done using encodeURIComponent(). encodeURIComponent() can encode characters (‘#’,’&’,’$’,’/’,’:’,’;’,’@’,’?’) which cannot be encoded by encodeURI() method. The syntax for encodeURIComponent() method is
Where, value is any value which is Boolean, string, and the number is converted to string before encoding. The return value is an encoded string.
Example 3
This is an example program to encode a string using encodeURIComponent() method.
The output for the above example program is −