I have text fields where a user can enter any characters. So if a user enters something like
<script>alert('hello')</script>
the data will be saved in the db like
<script>alert('hello')</script>
And when I display this data again we decode it so it appears the way it was entered.
What I am trying to do is create a file with all the characters that a user will be allowed to enter in a text field. The file is defined like this
< <
> >
' '
" "e;
+ +
¿ ¿
Each character and it's code separated by a space in a new line. I wrote a webmethod in a webservice that returns an array.
The code in the service is
public string[] GetCharacters()
{
string[] lines = File.ReadAllLines(Server.MapPath("~/scripts/EncodingChars/CharacterList.txt"));
return lines;
}
In my script file I am calling an ajax function that returns this array.
function DecodeText() {
$.ajax({
type: "POST",
url: "myService.asmx/GetCharacters",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: DecodeFileSuccess,
failure: function (data) {
alert(data.d);
}
});
}
function DecodeFileSuccess(response) {
var chars = response.d;
var textFields = $("textarea, input:text").not("input:hidden");
textFields.each(function (e) {
if ($(this).val()) {
var content = $(this).val();
$.each(chars, function (index, val) {
var char = val.split(" ");
content = content.replace(char[1], char[0]);
$(this).val(content);
});
}
});
}
I am trying to loop the array and replace the encoded value with the actual character. But it is not working. If I do something directly like
content = content.replace(/\</g, "<");
it works.
What am I doing wrong in the loop below that it is not replacing the encoded values with the special character?
$.each(chars, function (index, val) {
var char = val.split(" ");
content = content.replace(char[1], char[0]);
$(this).val(content);
});
Thanks