1

I'm inserting content with js, that includes an onclick call to a function. This function passes a parameter which contains a database entry, which could contain a ' .

var action = '<a href="#" class="facebook-share" onclick="facebookWallPost(\' '+name+'\')">Share</a>';

Trouble is that when name contains a single apostrophe it breaks the function call. I've tried doing a string replace on name to replace ' with &#39; but this seems to still be converted back to a ' by the browser.

Any idea how I can get around this?

Mr. Polywhirl
  • 35,562
  • 12
  • 75
  • 123
user3429445
  • 91
  • 2
  • 8

2 Answers2

1

Use escape() or after JavaScript version 1.5. use encodeURI() or encodeURIComponent() instead.

blue
  • 1,954
  • 1
  • 10
  • 8
0

Don't write code by mashing strings together with other code. You've got JavaScript inside HTML inside JavaScript and it is a recipe for headaches.

Use DOM manipulation instead.

var a = document.createElement('a');
a.href = "#"; // You should use a button instead of a link to the top of the page
a.className = "facebook-share";
a.addEventListener('click', function () {
    facebookWallPost(name);
});
a.appendChild(
    document.createTextNode('Share');
);
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264