str = str.
replace( /&(?!#?w ;)/g , '&').
replace( /undefinedundefined([^undefinedundefined]*)"/g , '"$1"' ).< ;br />
replace( /
replace( />/g , '>' ).
replace( /…/g , '…' ).
replace( /“/g , '"' ).
replace( /" /g , '"' ).
replace( /'/g , ''' ).
replace( /'/g , ''' ).
replace( /—/g , '—' ).
replace( /–/g , '–' );
The above is quite short. I have seen some JS codes in forums. When converting Wind Code into HTML, it is really crazy to write 20 or 30 lines. In fact, we can compare these matching patterns with the replaced ones. Characters are put into a hash, and then replaced in one go. 🎜>var hash = {
'<' : '<' ,
'>' : '>',
'…' : '…', '"' : '"' , '"' : '"' , ''' : ''' , ''' : ''' , '—' : '—', '–' : '–'
};
str = str.
replace( /&(?!#?w ;)/g , '&' ).
replace( /undefinedundefined ([^undefinedundefined]*)"/g , '"$1"' ).
replace( /[<>...""''—–]/g , function ( $0 ) {
return hash [ $0 ];
});
But this flaw is also obvious. For example, the hash key must be a simple ordinary string and cannot be a complex regular string. This is why we have to separate reasons. The replace function is not supported in older browsers. For this reason, we have to give up the last replace method above, and the replacement method is unified into an ordinary string.
Copy code
The code is as follows:
String.prototype.multiReplace = function ( hash ) {
var str = this, key;
Object.prototype.hasOwnProperty.call( hash , key ) is used to filter methods and properties inherited from the prototype. In this way, use is simple:
Copy code
The code is as follows:
str = str .multiReplace({
'&(?!#?\w ;)' :'&',
''' : ''' ,
'—' : '—',
'–' : '–'
} );
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn