This technique is widely used in Form Verification, syntax highlighting, and hazardous character filtering. If a paragraph is long and we don't want to replace it as below, we have to find a solution.
The Code is as follows:
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 ,'-');
The above is a little short. I have read some JS Code from the Forum. When converting Wind Code into HTML, It's really crazy to write 20 or 30 lines. In fact, we can put these matching modes and replaced characters into a hash, and then replace them with one breath.
The Code is as follows:
Var hash = {
'<': '<',
'>': '> ',
'... ':'... ',
':',
'"':'"',
''':''',
''':''',
'-':'-',
'-':'-'
};
Str = str.
Replace (/&(?! #? \ W +;)/g ,'&').
Replace (/undefinedundefined ([^ undefinedundefined] *) "/g, '" 1 "').
Replace (/[<>... "" ''--]/G, function ($0 ){
Return hash [$0];
});
However, this defect is also obvious. For example, the hash key must be a simple common string and cannot be a complex regular expression. This is why we have to separate it. Replace does not support functions in earlier browsers. Therefore, we had to discard the last replace method above and replace it with a common string.
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 attributes inherited from the prototype. In this way, it is easy to use:
The Code is as follows:
Str = str. multiReplace ({
'&(?! #? \ W + ;)':'&',
'Undefinedundefined ([^ undefinedundefined] *) ": '$ 1 "',
'<': '<',
'>': '> ',
'... ':'... ',
':',
'"':'"',
''':''',
''':''',
'-':'-',
'-':'-'
});