Write javascript code in url

encodeURI()

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to encodeURIComponent() , this function encodes fewer characters, preserving those that are part of the URI syntax.

Try it

Syntax

Parameters

A string to be encoded as a URI.

Return value

A new string representing the provided string encoded as a URI.

Exceptions

Description

encodeURI() is a function property of the global object.

The encodeURI() function escapes characters by UTF-8 code units, with each octet encoded in the format %XX , left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause encodeURI() to throw a URIError .

encodeURI() escapes all characters except:

The characters on the second line are characters that may be part of the URI syntax, and are only escaped by encodeURIComponent() . Both encodeURI() and encodeURIComponent() do not encode the characters -.!~*'() , known as «unreserved marks», which do not have a reserved purpose but are allowed in a URI «as is». (See RFC2396)

The encodeURI() function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning:

http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor

Examples

encodeURI() vs. encodeURIComponent()

encodeURI() differs from encodeURIComponent() as follows:

const set1 = ";/?:@&=+$,#"; // Reserved Characters const set2 = "-.!~*'()"; // Unreserved Marks const set3 = "ABC abc 123"; // Alphanumeric Characters + Space console.log(encodeURI(set1)); // ;/?:@&=+$,# console.log(encodeURI(set2)); // -.!~*'() console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20) console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // -.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20) 

Note that encodeURI() by itself cannot form proper HTTP GET and POST requests, such as for XMLHttpRequest , because & , + , and = are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent() , however, does encode these characters.

Encoding a lone high surrogate throws

A URIError will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:

// High-low pair OK encodeURI("\uD800\uDFFF"); // "%F0%90%8F%BF" // Lone high surrogate throws "URIError: malformed URI sequence" encodeURI("\uD800"); // Lone low surrogate throws "URIError: malformed URI sequence" encodeURI("\uDFFF"); 

You can use String.prototype.toWellFormed() , which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use String.prototype.isWellFormed() to check if a string contains lone surrogates before passing it to encodeURI() .

Читайте также:  Соединить элементы массива python

Encoding for RFC3986

The more recent RFC3986 makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ‘, (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format.

function encodeRFC3986URI(str)  return encodeURI(str) .replace(/%5B/g, "[") .replace(/%5D/g, "]") .replace( /[!'()*]/g, (c) => `%$c.charCodeAt(0).toString(16).toUpperCase()>`, ); > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 3, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to Write JavaScript Function as URL in Hyperlink?

You can write JavaScript function as URL in hyperlink on “href” attribute of …. tag. Writing JavaScript codes in a URL is another way of creating a link. We can include JavaScript code in the client-side using javascript: protocol specifier. This special protocol type specifies that the body of the URL is an arbitrary string of JavaScript code to be run by the JavaScript interpreter

. The “resource” identified by a javascript: URL is the return value of the executed code, converted to a string. If the code has an undefined return value, the resource has no content.

The syntax for writing JavaScript function

Following is the syntax for writing JavaScript function within href attribute of tag.

Similarly, the following is the syntax for writing JavaScript function within the action attribute of a tag.

Examples

Here is an example, where you will get a new date using javascript function as a hyperlink.

While using such functions on a hyperlink, some browsers like Firefox and IE execute the code in the URL. Then use the returned string as the content of a new document to display. Just as when following a link to an http: URL, the browser erases the current document and displays the new one. The value returned by the code above does not contain any HTML tags. Other browsers like chrome and safari do not allow URLs like the one above to overwrite the containing document, they just ignore the return value of the code. But they support the JavaScript code to display the returned content on the alert box as below.

If you want to open a new document using a javascript: URL which overwrites the current document, you can use location.replace method as given below.

Like HTML event handler attributes, JavaScript URLs are a holdover from the early days of the web and generally avoided in modern HTML. JavaScript: URLs are very useful if you need to test a small snippet of JavaScript code. You can type a javascript: URL directly into the location bar of your browser. And another most powerful use of Javascript: URLs is in browser bookmarks.

Источник

Cody Taylor

So it seems that most of the popular web browsers will allow you to write javascript where you normally put the url address. I thought this was kinda neat.

If you put something like ‘javascript:alert(“it works”);’ into the url field of your browser you should get a popup that says ‘it works’. This can be used to change any attribute on whatever page you are currently looking at. All you need to do is browse to the desired page and put something like the following into the url bar in your browser.

Of course this will only work on pages that contain a div or p element with the id of title (which most sites have).
I did have some issues with this depending on the browser used. Some browsers, like firefox 3.0.10 on Ubuntu Linux would just show me a blank page with Fake Title on it. This was solved by putting the javascript statements in an anonymous function in the url line.

This is all good and fun for small little tweaks but what if you wanted to do something a little more… crafty.
It is possible to include an external javascript file and alter the page so that you can execute your own little script from a specific domain. Have you ever been playing around with some ajax and gotten an ‘Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)’ error message? Well the method outlined below would allow you to put some proper ajax code into the site that isn’t allowing your requests.

While I’m not going to explain explicitly how to do anything fun I will show you how to include an external javascript file into a page in your browser that will allow you to call functions from that file on the page. Even though this will include the script you will still have to call a function from the script in the url bar. The code in the script will not execute by itself just because you included it.

The snippet above should all be one line. So if you paste that long one liner into the url bar of your preferred browser the javascript file from the url specified (http://quick-content.com/include_me.js) will be included into the html. At the very end of that statement I call the test() function that just changes the title of my blog to ‘Tech Stuff From Null’ as opposed to ‘Tech Stuff From Cody Taylor’. Try it out. Paste that code into your browser as you’re looking at my blog and check the title. This will work for any js file so have fun and don’t break anything.

Share

This entry was posted on Tuesday, June 2nd, 2009 at and is filed under . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Источник

JavaScript URL Encode Example – How to Use encodeURIcomponent() and encodeURI()

Shruti Kapoor

Shruti Kapoor

JavaScript URL Encode Example – How to Use encodeURIcomponent() and encodeURI()

You might think that encodeURI and encodeURIComponent do the same thing, at least from their names. And you might be confused which one to use and when.

In this article, I will demystify the difference between encodeURI and encodeURIComponent .

What is a URI and how is it different from a URL?

URI stands for Uniform Resource Identifier.
URL stands for Uniform Resource Locator.

Anything that uniquely identifies a resource is its URI, such as id, name, or ISBN number. A URL specifies a resource and how it can be accessed (the protocol). All URLs are URIs, but not all URIs are URLs.

Why do we need to encode?

URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded.

This means that we need to encode these characters when passing into a URL. Special characters such as & , space , ! when entered in a url need to be escaped, otherwise they may cause unpredictable situations.

  1. User has submitted values in a form that may be in a string format and need to be passed in, such as URL fields.
  2. Need to accept query string parameters in order to make GET requests.

What is the difference between encodeURI and encodeURIComponent?

encodeURI and encodeURIComponent are used to encode Uniform Resource Identifiers (URIs) by replacing certain characters by one, two, three or four escape sequences representing the UTF-8 encoding of the character.

encodeURIComponent should be used to encode a URI Component — a string that is supposed to be part of a URL.

encodeURI should be used to encode a URI or an existing URL.

Which characters are encoded?

encodeURI() will not encode: ~!@#$&*()=:/,;?+’

encodeURIComponent() will not encode: ~!*()’

The characters A-Z a-z 0-9 — _ . ! ~ * ‘ ( ) are not escaped.

Examples

const url = 'https://www.twitter.com' console.log(encodeURI(url)) //https://www.twitter.com console.log(encodeURIComponent(url)) //https%3A%2F%2Fwww.twitter.com const paramComponent = '?q=search' console.log(encodeURIComponent(paramComponent)) //"%3Fq%3Dsearch" console.log(url + encodeURIComponent(paramComponent)) //https://www.twitter.com%3Fq%3Dsearch 

When to encode

encodeURI("http://www.mysite.com/a file with spaces.html") //http://www.mysite.com/a%20file%20with%20spaces.html 
 let param = encodeURIComponent('mango') let url = "http://mysite.com/?search=" + param + "&length=99"; //http://mysite.com/?search=mango&length=99 

let params = encodeURIComponent(‘mango & pineapple’) let url = «http://mysite.com/?search summary»>Summary

If you have a complete URL, use encodeURI . But if you have a part of a URL, use encodeURIComponent .

Interested in more tutorials and JSBytes from me? Sign up for my newsletter. or follow me on Twitter

Источник

Оцените статью