来自司徒正美,比较方便的关键符号替换。

司徒正美认为:
不用多言,这种技术被广泛应用于表单验证,语法高亮和危险字符过滤中。一段话如果很长,如果不想像下面那样替换,我们得想些办法了。

他先给了个简单的例子:

var hash = {
'<' : '&lt;' , '>' : '&gt;', '…' : '&hellip;', '“' : '&ldquo;' , '”' : '&rdquo;' , '‘' : '&lsquo;' , '’' : '&rsquo;' , '—' : '&mdash;', '–' : '&ndash;'
};

str = str.
replace( /&(?!#?\w+;)/g , '&amp;' ).
replace( /"([^"]*)"/g , '“$1”' ).
replace( /[<>…“”‘’—–]/g , function ( $0 ) {
return hash[ $0 ];
});

并表示:缺陷也很明显,如哈希的键必须是简单的普通字符串,不能是复杂正则,这就是我们不得不分开的原因。replace在老一点的浏览器是不支持function的。为此,我们只好放弃上面最后那个replace方式,替换方统一为普通字符串。

于是,他扩展的String的基类,添加了一个方法:

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;'
});

Look,多简单啊。如果觉得我这里的表示更简单的话,请看原文http://www.cnblogs.com/rubylouvre/archive/2009/10/12/1581094.html