javascript特殊字符过滤函数

<script type="text/javascript">
<!--

var str = '<ok>,-';

// 用Hash存储进行正则替换
String.prototype.multiReplace = function(hash){
    
var str = this, key;
    
for(key in hash){
        
if(Object.prototype.hasOwnProperty.call(hash, key)){
            str 
= str.replace(new RegExp( key, 'g'), hash[key]);
        }
    }
    
return str;
}
str 
= str.multiReplace({
    
'&(?!#?\\w+;)' : '&amp;'   ,
    
'"([^"]*)"'    : '“$1”'    ,
    
'<'            : '&lt;'    ,
    
'>'            : '&gt;'    ,
    
''            : '&hellip;',
    
''            : '&ldquo;' ,
    
''            : '&rdquo;' ,
    
''            : '&lsquo;' ,
    
''            : '&rsquo;' ,
    
''            : '&mdash;' ,
    
''            : '&ndash;'
});
alert(str);

//-->
</script>

运用Hash结构存放 方便操作

原文地址:https://www.cnblogs.com/naoguazi/p/1771933.html