Horje
How to Escape a String in JavaScript?

Escaping a string in JavaScript is essential when you need to include special characters within a string literal without causing syntax errors or unintended behavior. Special characters, such as quotes, backslashes, and control characters, need to be treated differently to be represented correctly within a string. Escaping ensures these characters are interpreted correctly by the JavaScript engine.

These are the following approaches:

Using Backslashes

The most straightforward way to escape characters is by using backslashes (\). This method allows you to include special characters like quotes (” or ‘), backslashes, and control characters within a string.

Example: This example shows the escape of string using backslash.

JavaScript
let str = "This is a \"test\" string.";
console.log(str);  

Output
This is a "test" string.

Using Template Literals

Template literals, enclosed by backticks (`), allow embedding expressions and multiline strings. Special characters within template literals do not need escaping as rigorously as in regular strings.

Example: This example shows the escape of string using template literals.

JavaScript
let str = `This is a "test" string.`;
console.log(str); 

Output
This is a "test" string.

Using encodeURIComponent() and decodeURIComponent()

These methods are used to encode and decode special characters within URLs. They are useful when dealing with query strings or URL parameters to ensure special characters are properly encoded.

Example: This example shows the escape of string using encodeURIComponent() and decodeURIComponent().

JavaScript
let str = 'This is a "test" string.';
let encodedStr = encodeURIComponent(str);
let decodedStr = decodeURIComponent(encodedStr);
console.log(decodedStr);

Output
This is a "test" string.



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript String bold() Method JavaScript String bold() Method
JavaScript String fontsize() Method JavaScript String fontsize() Method
JavaScript String link() Method JavaScript String link() Method
JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search
JavaScript Program to Return the Previous Left Sibling JavaScript Program to Return the Previous Left Sibling

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15