Home > Software engineering >  How to escape single quote inside jQuery variable
How to escape single quote inside jQuery variable

Time:12-18

I have a jQuery with the following code:

id = 100;
name = "O'Keefe";
str = "<button type='button' onclick='selName( " id ",\"" name "\")'>Select</button>";

str is loaded into a div.

When I inspect the page it shows:

<button type="button" onclick="selName( 100, "O" Keefe")'>Select</button>

I tried escaping the single quote with

name = name.replace(/'/g, '\'');

But it didn't work.

My code works fine for names without single quote.

Any suggestions on how to deal with names with single quote?

Thanks.

CodePudding user response:

Don't use a string for that. Since you say you're using jQuery, you should attach the event listener with jQuery, not with inline events (which have a large number of problems, including this one - tedious quote escaping).

const button = $('<button>Select</button>')
  .on('click', () => selName(id, name))
  .appendTo('selectorOfWhateverYouWantToAppendThisTo');

CodePudding user response:

I found a solution.

id = 100;
name = "O'Keefe";
name = name.replace(/'/g, '&#39;'); //replace single quotes
str = "<button type='button' onclick='selName(" id ",\"" name "\")'>Select</button>";

When I replace the single quotes with &#39; the html shows:

<button type="button" onclick="selName( 100, "O'Keefe")">Select</button>

This works. Thanks.

  • Related