利用Javascript中每个对象(Object)的prototype属性我们可以为Javascript中的内置对象添加我们自己的方法和属性。
以下我们就用这个属性来为String对象添加三个方法:Trim,LTrim,RTrim(作用和VbScript中的同名函数一样)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); } String.prototype.LTrim = function() { return this.replace(/(^\s*)/g, ""); } String.prototype.Rtrim = function() { return this.replace(/(\s*$)/g, ""); }
|
下面看一个使用的实例:
1 2 3 4 5 6 7 8 9 10
| <script language=javascript> String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); } var s = " leading and trailing spaces "; window.alert(s + " (" + s.length + ")"); s = s.Trim(); window.alert(s + " (" + s.length + ")"); </script>
|
说明:
^ 匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。要匹配 ^ 字符本身,请使用 ^。
\s 与任何白字符匹配,包括空格、制表符、分页符等。等价于”[ \f\n\r\t\v]”。
$ 匹配输入的结尾。
- 匹配前一个字符零次或几次。例如,”zo*”可以匹配”z”、”zoo”。
/g 好像是全局匹配吧