What is encodeuricomponent in javascript

encodeURIComponent

Метод encodeURIComponent заменяет все символы, кроме:
символов латинского алфавита, десятичных цифр и — _ . ! ~ * ‘ ( ) .

Чтобы избежать некорректных запросов к серверу, метод encodeURIComponent следует вызывать на каждом введенном пользователем параметре, который будет передан как часть URI.

Например, пользователь может ввести «me&time=5» в переменной label . Без использования encodeURIComponent соответствующая компонента запроса будет иметь вид label=me&time=5 .
Вместо одного значения label появилось два значения:
label=me и time=5 .

Чтобы этого избежать, кодируйте данные перед передачей в URI:

label = 'me&you' uri = uri + '&label=' + encodeURIComponent(label)

См. также

У меня в FireFox encodeUriComponent оставляет русские буквы русскими

URI у вас закодирован, но уже сам браузер декодирует его обратно, для наглядности, чтобы в адресной строке вы видели текст, а не текст %D0%2F .

Что-то я не нашел в списке глобальных функций похожую на
encodeURIComponent функцию escape и обратную ей unescape. В чем разница между encodeURIComponent и escape?

Из своего опыта я заметил, к примеру, что escape кодирует пробел как %20, а если данные передаются из формы просто по submit, то пробел заменяется на ‘+’. Если применить unescape, то ‘+’ не будет заменен на пробел (по крайней мере, в FireFox).

Читайте также:  Special character codes html

а что у нас с поддержкой мобильными браузерами?

Надо видно посидеть разобраться. Что-то я ничего пока не могу понять. Да к тому же не особо силён в программировании. Пойду читать азбуку.

Подскажите, а как при помощи JavaScript вычислить человека по IP?

function findHumanByIP(HumanIPaddress) var db = window.connect(ANB-people-database);
var human = findHuman(db, HumanIPaddress);
kickAss(human);
>

Можно kickAss() еще глянуть?

/*. */ window.connect(ANB-people-database);

посмеялся
вот продолжение:

Помогите разобраться.
Посылаю запрос формируя адрес так

var link = «a:b:c»; var url = «documents/test.html» + «&link :», то выскакивает ошибка, 404. Если ставлю, например точки «a.b.c», то всё нормально работает.

Почему такая нелюбовь к двоеточиям?

Отправить комментарий

  • Полезные.
  • Дополняющие прочитанное.
  • Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены.
    Для остальных вопросов и обсуждений есть форум.

Учебник javascript

Основные элементы языка

Сундучок с инструментами

Интерфейсы

Все об AJAX

Оптимизация

Разное

  • Асинхронное программирование
  • Google Gears в деталях
  • Javascript Flash мост
  • Букмарклеты и правила их написания
  • О подборке книг на сайте
  • Почему — плохо
  • Способы идентификации в интернете
  • Уровни DOM
  • Что почитать?
  • Шаблонизация с javascript
  • Юнит-тесты уровня браузера на связке Selenium + PHP.
  • Справочники: Javascript/HTML/CSS
  • Система сборки и зависимостей Google Closure Library
  • Хранение данных на клиенте. DOM Storage и его аналоги.
  • 10 лучших функций на JavaScript
  • a href=»https://handgun-shop.
    1 час 5 секунд назад
  • a href=»https://handgun-shop.
    1 час 5 секунд назад
  • a href=»https://handgun-shop.
    1 час 5 секунд назад
  • a href=»https://handgun-shop.
    1 час 5 секунд назад
  • a href=»https://handgun-shop.
    1 час 11 минут назад
  • I really like your content i have also.
    1 час 34 минуты назад
  • https://wonkachocolatebars.com
    15 часов 19 минут назад
  • packman disposables
    15 часов 21 минута назад
  • packman disposables
    15 часов 21 минута назад
  • Adderall XR
    15 часов 22 минуты назад

Источник

encodeURIComponent()

The encodeURIComponent() 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 encodeURI() , this function encodes more characters, including those that are part of the URI syntax.

Try it

Syntax

encodeURIComponent(uriComponent) 

Parameters

A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are converted to strings.

Return value

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

Exceptions

Thrown if uriComponent contains a lone surrogate.

Description

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

encodeURIComponent() uses the same encoding algorithm as described in encodeURI() . It escapes all characters except:

Compared to encodeURI() , encodeURIComponent() escapes a larger set of characters. Use encodeURIComponent() on user-entered fields from forms POST ‘d to the server — this will encode & symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes Jack & Jill , without encodeURIComponent() , the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

For application/x-www-form-urlencoded , spaces are to be replaced by + , so one may wish to follow a encodeURIComponent() replacement with an additional replacement of %20 with + .

Examples

The following example provides the special encoding required within UTF-8 Content-Disposition and Link server response header parameters (e.g., UTF-8 filenames):

const fileName = "my file(2).txt"; const header = `Content-Disposition: attachment; filename*=UTF-8''$encodeRFC5987ValueChars( fileName, )>`; console.log(header); // "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt" function encodeRFC5987ValueChars(str)  return ( encodeURIComponent(str) // The following creates the sequences %27 %28 %29 %2A (Note that // the valid encoding of "*" is %2A, which necessitates calling // toUpperCase() to properly encode). Although RFC3986 reserves "!", // RFC5987 does not, so we do not need to escape it. .replace( /['()*]/g, (c) => `%$c.charCodeAt(0).toString(16).toUpperCase()>`, ) // The following are not required for percent-encoding per RFC5987, // so we can allow for a little better readability over the wire: |`^ .replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16)), ) ); > 

Encoding for RFC3986

The more recent RFC3986 reserves !, ‘, (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the IPv6 URI syntax. An RFC3986-compliant encodeURI implementation should not escape them, which is demonstrated in the encodeURI() example.

function encodeRFC3986URIComponent(str)  return encodeURIComponent(str).replace( /[!'()*]/g, (c) => `%$c.charCodeAt(0).toString(16).toUpperCase()>`, ); > 

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 encodeURIComponent("\uD800\uDFFF"); // "%F0%90%8F%BF" // Lone high surrogate throws "URIError: malformed URI sequence" encodeURIComponent("\uD800"); // Lone low surrogate throws "URIError: malformed URI sequence" encodeURIComponent("\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 encodeURIComponent() .

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.

Источник

The encodeURIComponent() Function in JavaScript

The encodeURIComponent() function in JavaScript allows you to encode special characters in your query string that would otherwise change the meaning of your query string.

Characters like + , / , and & are special. For example, suppose you wanted to send an HTTP request with the user’s email address in the query string.

fetch(`https://httpbin.org/get?email=$ `);

What happens if email has an & , like ‘john@gmail.com&param=somethingelse’ ? That would add an extra parameter param=somethingelse to the query string.

encodeURIComponent() ensures that email . For example:

const email = 'john@gmail.com¶m=somethingelse'; await fetch(`https://httpbin.org/get?email?email=$ `). then((res) => res.json()); // await fetch(`https://httpbin.org/get?email=$encodeURIComponent(email)>`). then((res) => res.json()); // 

Do not encode the entire url! Just encode the individual values in the query string.

Axios

If you’re using Axios query params, you don’t need to use encodeURIComponent() . Axios calls encodeURIComponent() for you.

const axios = require('axios'); // Equivalent to `axios.get('https://httpbin.org/get?answer=42')` const res = await axios.get('https://httpbin.org/get', < params: < answer: 42 > >); res.data.args; // 

More Fundamentals Tutorials

Источник

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

Источник

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