YogeshChauhan . com

Did you get an error while displaying Special Characters in JavaScript?

in JavaScript on June 18, 2019

We use strings in JavaScript to store texts. Strings are stored in “Quotes”, even if the value is null or empty it should be written in quotes. We can either use single quotes or double quotes, it doesn’t matter.

Now what if you want to display quotes itself to make the sentence standout?

You can use quotes inside the quotes, as long as inside quotes and outside quotes are different for e.g.


  var blog = "This is my 'blog'";
  var blog2 = 'It is called "The Coding Yogi"';

Now things are pretty fine until now. But it gets messy when you want to use double quotes inside the double quotes as well as special characters inside the string quotes. for example a backslash (\).

Look at the example below..


  var x = "This blog named "The Coding Yogi" is helpful.";

  /* Output */
  This blog named is helpful.

Now you’ve understood he problem of using double quotes inside the double quotes. The same error occurs while using single quotes inside single quote.

So what to do?

To avoud that problem, we can use “backslash escape character”. It just magically (no magic in coding — just logic) turns special characters into string characters.

So, { \’ } becomes { ‘ } — single quote

{ \” } becomes { ” } — double quote and

{ \\ } becomes { \ } — backslash

So the example above with an error can be rewritten as below.


  var x = "This blog named \"The Coding Yogi\" is helpful.";

  /* Output */
  This blog named "The Coding Yogi" is helpful.

In JavaScript, if you want to add “apostrophe s” then you should use backslash. For e.g.


  var x = 'It\'s great.';

  /* Output */
  It's great.

And for a backslash itself…. just use double backslashes just like…


  var x = "Just like this \\ backslash.";

  /* Output */
  Just like this \ backslash.
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

INTERSECT and EXCEPT in PostgresPostgresHow to create Glowing Text using CSS?CSSWhat happens when we add Numbers and Strings in JavaScript?JavaScriptUPDATE and DELETE Statements in PostgresPostgresURL paths in DrupalDrupalHow states work in React?React