views:

232

answers:

1
return mystring.replace(/&/g, "&").replace(/>/g, ">")  
      .replace(/</g, "&lt;").replace(/"/g, "&quot;");

The above is my code, and I guess since it tracks the string 4 times, it makes it slower. Is there any other way (method prefered) to replace those special characters in only one loop? Well I can do it with a for loop and checking char by char, but it is not smthing I would like to.

Thanks.

+5  A: 

HtmlEncode and HtmlDecode should work. I'll add more info in a minute.


Here's a link to MSDN.

Of course - i'm assuming that's what you are trying to achieve and other kind of string replacements are not necessary.


Forgot to add - i haven't done any performance tests. And yet - it`s supposed to work faster.

Arnis L.
As Arnis says, if you're just trying to encode HTML into entities you should use HtmlEncode.
Mark B
Sorry, didn't notice you'd already accepted the answer!
Mark B