s="[script]xss()[/script]foo[s]foo[/s]" re=/(\[)|(\])/g alert(s.replace(re, function(a, b, c){if(a===b) return "<"; if(a===c) return">"}))