Escape method in javascript

escape()

Устарело: Эта возможность была удалена из веб-стандартов. Хотя некоторые браузеры по-прежнему могут поддерживать её, она находится в процессе удаления. Не используйте её ни в старых, ни в новых проектах. Страницы или веб-приложения, использующие её, могут в любой момент сломаться.

Устаревший метод escape() возвращает новую строку, в которой определённые символы заменены шестнадцатеричной управляющей последовательностью. Используйте методы encodeURI или encodeURIComponent вместо него.

Синтаксис

Параметры

Описание

Функция escape() является свойством глобального объекта, т.е. относится к глобальным функциям. Эта функция кодирует специальные символы, за исключением: @*_+-./

The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: %xx. For characters with a greater code unit, the four-digit format %uxxxx is used.

Примеры

escape("abc123"); // "abc123" escape("текст"); // "%u0442%u0435%u043A%u0441%u0442" escape("ć"); // "%u0107" /* специальные символы */ escape("@*_+-./"); // "@*_+-./" 

Спецификации

Browser compatibility

BCD tables only load in the browser

Читайте также:  Анимация html бегущая строка

See also

Found a content problem with this page?

This page was last modified on 28 окт. 2022 г. 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.

Источник

What are escape and unescape String Functions in JavaScript

In JavaScript, escape() and unescape() methods are used to encode and decode strings. The JavaScript method unescape() can be used to restore the original string after using the escape() function to make a string accessible for transmission over a network.

This article will describe the escape and unescape functions in JavaScript.

What are escape String Functions in JavaScript?

The “escape()” function encodes the string to make it accessible for network transmission. It encodes all the non-ASCII characters to their two or four-digit hexadecimal numbers. Moreover, a blank space is converted to “%20” by the escape function.

Follow the given syntax to use the escape() method:

Here, “string” is the parameter passed in a method for encoding.

Example

First, create a string named “str”:

Print the string on the page using the “document.write()” method:

Call the escape() method by passing a string as an argument and store the resultant encoded string in a variable “encodeStr”:

Finally, print the encoded string on the page:

The output shows the original and encoded strings. Here, you can see that the “spaces” converted to “%20”, “(“ to “%28”, “!” to “%21” and “)” to “%29”:

What are unescape String Functions in JavaScript?

The unescape() method decodes the string in its original state. It converts all the hexadecimal values to the relevant character that they represent. Some browsers do not support this method, so for that, you can utilize the “ decodeURIComponent()” or “decodeURI()” as a replacement.

Use the below-mentioned syntax for decoding the encoded string using unescape() method:

It takes an encoded string as a parameter.

Here, call the unescape() method by passing an encoded string “encodeStr” as an argument:

Print the decoded string on the page:

The output displays original, encoded, and decoded strings:

That’s all about escape and unescape functions in JavaScript.

Conclusion

The escape and unescape functions are used for encoding and decoding the strings to make a string accessible for transmission over a network. The escape() method converts all the non-ASCII values to their hexadecimal numbers, and the unescape() method will convert the encoded string into its original string by converting hexadecimal values to their non-ASCII characters. In this article, we described the escape and unescape functions in JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

JavaScript escape()

Функция escape() deprecated устарела в JavaScript версии 1.5. Вместо этого используйте encodeURI() или encodeURIComponent().

Функция escape() кодирует строку.

Эта функция делает строку переносимой, поэтому ее можно передавать по любой сети на любой компьютер, поддерживающий символы ASCII.

Эта функция кодирует специальные символы, за исключением: * @ — _ + . /

Поддержка браузера

Синтаксис

Значения параметров

Технические детали

Мы только что запустили
SchoolsW3 видео

ВЫБОР ЦВЕТА

colorpicker

Сообщить об ошибке

Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:

Ваше предложение:

Спасибо Вам за то, что помогаете!

Ваше сообщение было отправлено в SchoolsW3.

ТОП Учебники
ТОП Справочники
ТОП Примеры
Получить сертификат

SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.

Источник

How to Escape a String in JavaScript – JS Escaping Example

Joel Olawanle

Joel Olawanle

How to Escape a String in JavaScript – JS Escaping Example

In JavaScript, a string is a data type representing a sequence of characters that may consist of letters, numbers, symbols, words, or sentences.

Strings are used to represent text-based data and are mostly defined using either single quotes ( ‘ ) or double quotes ( » ).

let name1 = 'John Doe'; let name2 = "John Doe"; 

Due to the fact that these quotation marks are used to denote strings, you need to be careful when using apostrophes and quotes in strings.

When you attempt to use them within a string, in an actual sense it will end the string, and JavaScript will attempt to parse the rest of the intended string as code. This will throw an error.

let quote = "He said, "I learned from freeCodeCamp!""; 

This will throw an error, as seen below:

Uncaught SyntaxError: Unexpected identifier 'I' 

In JavaScript, if you need to include quotes or apostrophes within a string, there are three major ways to fix the error. These methods are:

  • By using the opposite string syntax
  • Using an escape character
  • Using template literals

How to use Opposite String Syntax to Escape a String in JavaScript

In JavaScript, you can use the opposite string syntax ‘ or » to escape a string. To do so, you must wrap the string in the opposite syntax of what you are escaping.

let quote = 'He said, "I learned from freeCodeCamp!"'; console.log(quote); // He said, "I learned from freeCodeCamp!" let apostrophe = "It's a beautiful day"; console.log(apostrophe); // It's a beautiful day 

This means if you use double quotes to wrap your string, you can use an apostrophe within the string. Also if you wrap your string in single quotes, then you can use double quotes within the string.

But there are limitations to this because what if you have to use a quote and an apostrophe within the same string? Then you can use an escape character ( \ ).

How to Use the Escape Character ( \ ) to Escape a String in JavaScript

In JavaScript, you can escape a string by using the \ (backslash) character. The backslash indicates that the next character should be treated as a literal character rather than as a special character or string delimiter.

Here is an example of escaping a string in JavaScript:

let quote = "He said, \"I learned from freeCodeCamp!\""; console.log(quote); // He said, "I learned from freeCodeCamp!" let apostrophe = 'It\'s a beautiful day'; console.log(apostrophe); // It's a beautiful day 

How to Use Template Literals to Escape a String in JavaScript

In JavaScript, you can also use Template Literals (also known as Template Strings) to escape a string.

Template Literals are string literals that allow you to embed expressions inside a string, using the syntax $ .

let quote = `He said, "I learned from freeCodeCamp!"`; console.log(quote); // He said, "I learned from freeCodeCamp!" 

With Template Literals, you don’t need to use backslashes to escape characters. Instead, you simply wrap the string in backticks ( )

Wrapping Up!

In this article, you have learned how to escape a string in JavaScript. This will help you avoid using Unicode characters to add quotes and apostrophes within strings.

You can access over 180 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.

Источник

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