javascript替换字符

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


str = str.
	replace( /&(?!#?\w+;)/g , '&').
	replace( /"([^"]*)"/g   , '“$1”'   ).
	replace( /</g           , '&lt;'  ).
	replace( />/g           , '&gt;' ).
	replace( /…/g           , '&hellip;' ).
	replace( /“/g           , '&ldquo;'  ).
	replace( /”/g           , '&rdquo;'  ).
	replace( /‘/g           , '&lsquo;'  ).
	replace( /’/g           , '&rsquo;'  ).
	replace( /—/g           , '&mdash;' ).
	replace( /–/g           , '&ndash;'  );

上面这个还算短了,我看过一些论坛的JS代码,在把Wind Code转换成HTML时,那真是疯子似的写上二三十行。其实我们大可以把这些匹配模式与替换后的字符放到一个哈希中,然后一口气替换掉。


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.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;
};

Object.prototype.hasOwnProperty.call( hash, key )是用来过滤继承自原型的方法与属性的。这样一来,使用就简单了:


str = str.multiReplace({
	'&(?!#?\\w+;)' :'&amp;',
	'"([^"]*)" : '“$1”',
	'<' : '&lt;' ,
	'>' : '&gt;',
	'…' : '&hellip;',
	'“' : '&ldquo;' ,
	'”' : '&rdquo;' ,
	'‘' : '&lsquo;' ,
	'’' : '&rsquo;' ,
	'—' : '&mdash;',
	'–' : '&ndash;'
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值