0

This is probably a very simple question but it's several hours that I'm searching for a satisfying answer and haven't found any:

I am getting a string from the user but I want to sanitize and show it in an alert. The best I could come up with is to write the following function:

/**
 * This function replaces XML character entities. '&', '<' and '>' with '&amp;', '&lt;' and '&gt;' respectively.
 */
function sanitize ( str ) {
    if ( !str ) {
        return str;
    }
    return str.replace( '&', '&amp;' ).replace( '<', '&lt;').replace( '>', '&gt;');
}

It works. But the question is:

Isn't there any standard function in Javascript to sanitize a string more efficiently or natively? (I'm concerned about Chrome and Firefox)

Note: I've searched StackOverflow and threads like this one are not my answer.

Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104

1 Answers1

0

Would escape and unescape help you?

return escape(str);
Nathan Russell
  • 3,428
  • 5
  • 30
  • 51
  • Hmm, maybe my answer is not right - I guess it depends on what you want to do with the string. Your code suggests you want to use xml entities. IE. & becomes & etc. My suggestion of using escape turn & into & This might not be what you want? – Nathan Russell May 22 '12 at 20:43
  • Agreed Alex. Like I said, I guess it depends on what you are trying to do downstream with the sanitized string. – Nathan Russell May 22 '12 at 20:45