A more visual approach:
String.prototype.htmlProtect = function() {
var replace_map;
replace_map = {
'\n': '<br />',
'<': '<',
'>': '>'
};
return this.replace(/[<>\n]/g, function(match) { // be sure to add every char in the pattern
return replace_map[match];
});
};
and this is how you call it:
var myString = "<b>tell me a story, \n<i>bro'</i>";
var myNewString = myString.htmlProtect();
// <b>tell me a story, <br /><i>bro'</i>