本范例演示了JS中如何通过String.prototype自定义字符串操作协议,本代码定义了两个操作方法,一个用于清除html标签,一个用来转换html标签,都非常有用
String.prototype.stripslashes = function(){ return this.replace(/<.*?>/g, ''); }; String.prototype.htmlspecialchars = function(){ var str = this.replace(/&/g, '&'); str = str.replace(/</g, '<'); str = str.replace(/>/g, '>'); str = str.replace(/"/g, '"'); return str; }; //使用范例: var str = '<b>my personal website:</b> '; str += '<a href="http://www.jonasjohn.de/">jonasjohn.de</a>'; document.write("Original string (html): '" + str + "'<br/><br/>"); var str_no_html = str.stripslashes(); document.write("- String without HTML tags: '" + str_no_html + "'<br/>"); var str_hsc = str.htmlspecialchars(); document.write("- String with converted HTML tags: '" + str_hsc + "'");