平时用 JavaScript 的时候觉得它的 String 提供的工具方法太少,居然连 trim() 都没有。不过,通过 JavaScript 的 prototype,我们可以为 String 对象添加一些工具方法。如下面我们就添加了 trim(), startsWith(), endsWith(), iEquals() 等方法,之后还以 style() 方法为例扩展了 String 生成 HTML 代码 (如 bold, sup 等方法) 的功能。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>扩展 String 的方法</title> <style><!-- body, p, pre, td, th { font-size: 12px; } --></style> </head> <!-- 为 JScript/JavaScript 的 String 添加一些工具方法 --> <script language="JavaScript" type="text/JavaScript"> /** * 去掉字符串两端的空白字符 */ String.prototype.trim = function() { return this.replace(/(^/s+)|(/s+$)/g, ""); } /** * 忽略大小写比较字符串 * 注:不忽略大小写比较用 == 号 */ String.prototype.iEquals = function(str) { return this.toLowerCase() == str.toLowerCase(); } /** * 比较字符串,根据结果返回 -1, 0, 1 */ String.prototype.compareTo = function(str) { if (this == str) { return 0; } else if (this < str) { return -1; } else { return 1; } } /** * 忽略大小写比较字符串,根据结果返回 -1, 0, 1 */ String.prototype.iCompareTo = function(str) { return this.toLowerCase().compareTo(str.toLowerCase()); } /** * 判断字符串是否以指定的字符串开始 */ String.prototype.startsWith = function(str) { return this.substr(0, str.length) == str; } /** * 判断字符串是否以指定的字符串开始,忽略大小写 */ String.prototype.iStartsWith = function(str) { return this.substr(0, str.length).iEquals(str); } /** * 判断字符串是否以指定的字符串结束 */ String.prototype.endsWith = function(str) { return this.substr(this.length - str.length) == str; } /** * 判断字符串是否以指定的字符串结束,忽略大小写 */ String.prototype.iEndsWith = function(str) { return this.substr(this.length - str.length).iEquals(str); } /** * 构造特定样式的字符串,用 <span></span> 包含 */ String.prototype.style = function(style) { return "<span style=/"".concat(style, "/">", this, "</span>"); } </script> <!-- 以下 HTML 以对上面函数的测试 --> <body> <table border="0" cellpadding="5" cellspacing="1" align="center" bgcolor="#666666"> <tr bgcolor="#F8F8F8" height="30" valign="top"> <th>源字符串</th> <th>方法及参数</th> <th>结果</th> </tr> <script language="JavaScript" type="text/JavaScript"> // 测试某个方法 function test(str, mthd) { document.write("<tr bgcolor=/"#FFFFFF/" valign=/"middle/"><td><pre>" + str + "</pre></td><td><pre>" + mthd + "</pre></td><td><pre>" + eval("/"" + str + "/"." + mthd) + "</pre></td></tr>"); } // 开始测试 test(" Hello String ", "trim()"); test("Hello String", "style(/"color: #FF0000; background-color: #DDEEFF;/")"); test("Hello String", "iEquals(/"hello string/")"); test("Hello String", "compareTo(/"hello string/")"); test("Hello String", "iCompareTo(/"hello string/")"); test("Hello String", "startsWith(/"hello/")"); test("Hello String", "iStartsWith(/"hello/")"); test("Hello String", "endsWith(/"string/")"); test("Hello String", "iEndsWith(/"string/")"); </script> </table> </body> </html>