JavaScript 替换Html标签实现代码

(编辑:jimmy 日期: 2024/10/10 浏览:2)

复制代码 代码如下:
str = str.<br />
replace( /&amp;(?!#?\w+;)/g , '&amp;').<br />
replace( /undefinedundefined([^undefinedundefined]*)&quot;/g , '“$1”' ).<br />
replace( /&lt;/g , '&lt;' ).<br />
replace( /&gt;/g , '&gt;' ).<br />
replace( /…/g , '…' ).<br />
replace( /“/g , '“' ).<br />
replace( /”/g , '”' ).<br />
replace( /‘/g , '‘' ).<br />
replace( /'/g , ''' ).<br />
replace( /—/g , '—' ).<br />
replace( /–/g , '–' );

上面这个还算短了,我看过一些论坛的JS代码,在把Wind Code转换成HTML时,那真是疯子似的写上二三十行。其实我们大可以把这些匹配模式与替换后的字符放到一个哈希中,然后一口气替换掉。
复制代码 代码如下:
var hash = {
'<' : '<' ,
'>' : '>',
'…' : '…',
'“' : '“' ,
'”' : '”' ,
'‘' : '‘' ,
''' : ''' ,
'—' : '—',
'–' : '–'
};
str = str.
replace( /&(?!#?\w+;)/g , '&' ).
replace( /undefinedundefined([^undefinedundefined]*)"/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+;)' :'&',
'undefinedundefined([^undefinedundefined]*)" : '“$1”',
'<' : '<' ,
'>' : '>',
'…' : '…',
'“' : '“' ,
'”' : '”' ,
'‘' : '‘' ,
''' : ''' ,
'—' : '—',
'–' : '–'
});
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。