当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 替换Html标签实现代码

Javascript
MooTools教程(3):数组管理DOM元素
MooTools教程(4):函数和MooTools
MooTools教程(5):事件处理
MooTools教程(6):操纵HTML DOM元素
MooTools教程(7):设置和获取样式表属性
MooTools教程(8):输入过滤-数字
MooTools教程(9):输入过滤-字符串
MooTools教程(10):Fx.Tween渐变
MooTools教程(11):Fx.Morph、Fx选项和Fx事件
MooTools教程(12):Drag.Move来实现拖放
MooTools教程(13):正则表达式
MooTools教程(14):定时器和Hash对象
MooTools教程(15):滚动条(Slider)
浏览器对Cookie的限制
图片不间断滚动的特效代码详细讲解
Javascript教程:拖放效果研究
不唐突的JavaScript
JavaScript教程:图片切割效果
认识AJAX了解AJAX优点缺点和运用
网页投票系统中的限制

Javascript 中的 JavaScript 替换Html标签实现代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 411 ::
收藏到网摘: n/a

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

str = str.<br />
replace( /&(?!#?\w+;)/g , '&').<br />
replace( /undefinedundefined([^undefinedundefined]*)"/g , '“$1”' ).<br />
replace( /</g , '<' ).<br />
replace( />/g , '>' ).<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”',
'<' : '<' ,
'>' : '>',
'…' : '…',
'“' : '“' ,
'”' : '”' ,
'‘' : '‘' ,
''' : ''' ,
'—' : '—',
'–' : '–'
});