[SalesForce] visualforce: how to escape single-quotes in Javascript

I need to include a JavaScript statement in a visualforce page that includes single quote marks, like this:

formatter: function (cellvalue, options, rowObject) {

   var link = '';

   link = '<a href="#" ' + 
   'onClick="showInfoPopup(''' + rowObject.geocode + '''); return false;"' + 
   '>' + 'info' + '</a>';

    return link;

},

where rowObject is a JavaScript object in the page, not something coming from an Apex Controller.

I've tried using \' and ''', but I can't get my page to compile.

What is the proper way to escape single quote marks in a JavaScript statement in a Visualforce page?

Best Answer

To be clear, You can use both double quote (") and single quote (') to define a string in javascript, the condition is that the start and end character should be the same i.e. if you start string with double quote (") then you should end it with a double quote only. As you are rightly trying the escape character is backslash (). So, this code should work:-

var link = '<a href="#" onClick= "alert(\'' + rowObject.geocode + '\'); return false;">info</a>';
Related Topic