frenchie
frenchie

Reputation: 51947

Correctly escaping characters when generating dynamic HTML

I have the following code in a JS Fiddle:

function Start() {

    var TheData = 'tes"ss<div></div>t3\'k';

    var TheHTML = '<div class="SomeClass">' + TestXSS(TheData) + '</div>';
    TheHTML += '<input type="text" id="TheTextBox" value="';
    TheHTML += TestXSS(TheData) + '" />';

    $('#Dynamic').html(TheHTML);
}

function TestXSS(TheText) {

    TheText = TheText.replace('"', '&quot;');
    TheText = TheText.replace("'", '&#39;');
    TheText = TheText.replace('<', '&lt;');
    TheText = TheText.replace('>', '&gt;');

    return TheText;
}

As you can see, the HTML is dynamically generated and added to the DOM with jQuery, and there's also a function to escape characters that might cause problems. But in the fiddle, there's still an issue and so I was wondering how to correctly escape characters.

enter image description here

Upvotes: 0

Views: 924

Answers (2)

niko
niko

Reputation: 9393

TheText.replace('"', '&quot;'); // stops after first match

use g modifier for global match

TheText = TheText.replace(/"/g, '&quot;');

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).`

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

function TestXSS(TheText) {

    TheText = TheText.replace(/"/g, '&quot;');
    TheText = TheText.replace(/'/g, '&#39;');
    TheText = TheText.replace(/</g, '&lt;');
    TheText = TheText.replace(/>/g, '&gt;');

    return TheText;
}

Demo: Fiddle

Upvotes: 0

Related Questions