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.

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 14 How to add Google Map in WordPress using ACF? May 13 How to add a select dropdown in React? May 12 What are Controlled Components in React? May 11 How to create a full screen loader using CSS and JavaScript? May 11 How to hide and show menu on scroll using JavaScript and CSS? May 10 @use rule in SCSS (Sass)

You might also like these

Canvas Drawing in HTML5HTMLDid you get an error while displaying Special Characters in JavaScript?JavaScriptHow to position an image on top of another image using CSS?CSS:in-range and :out-of-range selector in CSSCSSWordPress: How to find all posts from a custom post type with multiple custom fields values?WordPressHow to create a Bootstrap style accordion using CSS and JavaScript?CSS