Home  >  Article  >  Web Front-end  >  JavaScript replacement Html tag implementation code_javascript skills

JavaScript replacement Html tag implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:44:361077browse
Copy code The code is as follows:

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;
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 ) 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 ;)' :'&',
'undefinedundefined([^undefinedundefined]*)" : '"$1"', '< ' : '<' , '>' : '>', '…' : '…', '"' : '"' , '"' : ' ''' , ''' : ''' ,
''' : ''' ,
'—' : '—',
'–' : '–'
} );