Selwyn
Selwyn

Reputation: 1621

Javascript special escaping characters

Hi I am using JavaScript function that is called from an anchor link which passes a title that has a special character could you please tell me how can I escape the single quote in the string passed to the function.

The sample string is given below,

string desc="test's/test2'w";

sample link html

"<a href="javascript:getdata(\'' + desc+ '\',);void(0);">TEST</a>"

so the function getdata is not called since it's not escaping that character.

Its a legacy system I will need to work with HTML only

Upvotes: 0

Views: 204

Answers (2)

Paul S.
Paul S.

Reputation: 66334

If you don't know the names of all the HTML entities, you can still HTML encode them

function htmlEncode(str) {
    return str.replace(/[^\da-z()\[\] .,\/\\]/g, function (m) {
        return '&#' + m.charCodeAt(0) + ';';
    });
}
htmlEncode("test's/test2'w"); // "test&#39;s/test2&#39;w"

Where \da-z()\[\] .,\/\\ is the white list of permitted characters.

If you want to generate HTML as Strings, this is okay, but if you want to make new DOM elements, Quentin's answer is much better in the long run.

Upvotes: 0

Quentin
Quentin

Reputation: 943571

Don't generate HTML by smashing together strings, use DOM. Don't use JavaScript URIs, use event handlers.

var desc = "test's/test2'w";
var link = document.createElement('a');
link.appendChild( document.createTextNode('TEST') );
link.href = "fallback.html";
link.addEventListener('click', function (evt) {
    getData(desc);
    evt.preventDefault();
});
document.body.appendChild(link);

Upvotes: 4

Related Questions