Search code examples
javascriptjsonescapingfreemarkerhtml-escape-characters

Escaping in JavaScript


How do I make this work? <a href='javascript:func("Jack'S Birthday")'>Jack's Birthday</a>


Solution

  • Do as follows:

    // How about using variables instead?
    var emily = "Emily'S Birthday"
    var birthdays = {
      john: "John'S Birthday"
    }
    
    function func(val) {
      console.log(val);
    }
    <!DOCTYPE html>
    <html>
    
    <body>
      <a href='javascript:func("Jack&apos;S Birthday")'>Jack's Birthday</a>
      <br>
      <a href="javascript:func('Norman\'S Birthday')">Norman's Birthday</a>
      <br>
      <a href="javascript:func(emily)">Emily's Birthday</a>
      <br>
      <a href="javascript:func(birthdays.john)">John's Birthday</a>
    </body>
    
    </html>

    Explanation:

    1. Keep single quotes within double quotes when you escape using backslash \
    2. Use double quotes within single quotes when you use $apos;
    3. Best of all, use variables, they ease a lot of pain -

      a. You don't have to go into html to modify values,
      b. these can be declared at one place, or a single file,
      c. They can be fetched from back-end
      d. Best yet, no need to deal with quotes!