title: adding escape character to a string in javascript
body: <pre><code>&lt;html&gt;
  &lt;body&gt;
  
  &lt;p id="demo"&gt;&lt;/p&gt;
  
  &lt;script&gt;
  
  var x = 'It\'s \@lright';
  var y = "We are the so-called \"Vikings\" from the north.";
  var i;
  var s = "";
  var z = "Thi$ is * a@ demo";
  var patt = "[^A-Za-z0-9\\s]";
  for(i=0;i&lt;z.length;i++){
    if(z[i].match(patt)){
      s+= "\\"+z[i];
    }
    else{
      s+= z[i];
    }
  }
  document.getElementById("demo").innerHTML = x + "&lt;br&gt;" + y + "&lt;br&gt;" + s;  
  
  &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The output for the above script I get is :</p>
  
  <blockquote>
    <p>It's @lright<br>
    We are the so-called "Vikings" from the north.<br>
    Thi\$ is \* a\@ demo</p>
  </blockquote>
  
  <p>I don't know why for the strings <code>x</code> and <code>y</code>, if I add any special character followed by <code>'\'</code> (backslash), strings are displayed as it is with the special characters. But when I do it to string s by appending <code>'\'</code> before each special character, the string gets displayed with <code>'\'</code> preceding the special characters. </p>
  
  <p>Can someone explain me this? And also please tell me how to add '\' before each special character in such a way that when I print the string I only see the special characters (not with <code>'\'</code> prepended in front of them as happening now)?</p>