>  기사  >  웹 프론트엔드  >  JavaScript 替换Html标签实现代码_javascript技巧

JavaScript 替换Html标签实现代码_javascript技巧

WBOY
WBOY원래의
2016-05-16 18:44:361032검색
复制代码 代码如下:

str = str.

replace( /&(?!#?\w+;)/g , '&').

replace( /undefinedundefined([^undefinedundefined]*)"/g , '“$1”' ).

replace( /, '
replace( />/g , '>' ).

replace( /…/g , '…' ).

replace( /“/g , '“' ).

replace( /”/g , '”' ).

replace( /‘/g , '‘' ).

replace( /'/g , ''' ).

replace( /—/g , '—' ).

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”',
''>' : '>',
'…' : '…',
'“' : '“' ,
'”' : '”' ,
'‘' : '‘' ,
''' : ''' ,
'—' : '—',
'–' : '–'
});
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.