GustyWind
GustyWind

Reputation: 3036

Escaping single quote creating unrequired "\" in the HTML page

I have to show the name of an employee on an HTML page and on mouse over the employee name again, as shown below.

enter image description here

There is a problem when employee name contains single quote in innerHTML value which is throwing the JavaScript error

missing ) after argument list
At line: 1

Using StringEscapeUtils.escapeJavaScript solves the JavaScript error but the actual HTML renderer retains the "\" before the single quote. How do I get rid of it?

Upvotes: 0

Views: 352

Answers (1)

Zecc
Zecc

Reputation: 4340

You simply can't use the same text in HTML and in JavaScript. They are different languages with different escaping needs.

Use StringEscapeUtils.escapeHtml() for HTML and StringEscapeUtils.escapeJavaScript() for JavaScript.

Edit: yes, show us the code that's generating the HTML. Perhaps you don't need to escape the text for HTML yourself if it's being done by someone else's code.

Upvotes: 5

Related Questions