Yogesh Chauhan's Blog

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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Here’s what we can do with PHP date() functionPHP2 Ways We Can Write Multiple Line Commands in PHPPHPHow to add a Line Chart in Angular App?AngularLearn to create profile card using HTML and CSSCSSHow to create a smooth scrolling effect with CSS?CSSCheck whether a variable exists and not empty in PHPPHP