Reputation: 51947
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('"', '"');
TheText = TheText.replace("'", ''');
TheText = TheText.replace('<', '<');
TheText = TheText.replace('>', '>');
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.
Upvotes: 0
Views: 924
Reputation: 9393
TheText.replace('"', '"'); // stops after first match
use g
modifier for global match
TheText = TheText.replace(/"/g, '"');
The g
modifier is used to perform a global match (find all matches rather than stopping after the first match).`
Upvotes: 1
Reputation: 388316
Try
function TestXSS(TheText) {
TheText = TheText.replace(/"/g, '"');
TheText = TheText.replace(/'/g, ''');
TheText = TheText.replace(/</g, '<');
TheText = TheText.replace(/>/g, '>');
return TheText;
}
Demo: Fiddle
Upvotes: 0