返回列表 发帖

[原生JavaScript] 扩展String原型实现Java的 trim 方法

总结一下,此trim 方法有几种使用方法:
trim()   去除字符串左右两端的空格
trim("xyz")  去除字符串左右两端的字符xyz
trim(/[0-9]/g)  去除字符串左右两端的数字
trim(2)  去除字符串左端2个字符
trim(0,3)  去除字符串右端3个字符
trim(2,3)  去除字符串左端2个字符右端3个字符
  1. String.prototype.trim = function(){
  2.     var _argument = arguments[0] == undefined ? " " : arguments[0];
  3.     if(typeof(_argument) == "string"){
  4.         if (_argument == " ") {
  5.             return this.replace(/(^(\s|\u3000)*)|((\s|\u3000)*$)/g, "");
  6.         } else {
  7.             return this.replace(new RegExp("(^" + _argument + "*)|(" + _argument + "*$)", "g"), "");
  8.         }
  9.     }else if(typeof(_argument) == "object"){
  10.         return this.replace(_argument, "");
  11.     }else if(typeof(_argument) == "number"){
  12.         if (arguments.length == 1) {
  13.             return this.substring(arguments[0])
  14.         } else if(typeof(arguments[1]) == "number") {
  15.             return this.substring(arguments[0], this.length-arguments[1]);
  16.         }
  17.     }
  18.     return this;
  19. };
复制代码

[ 本帖最后由 robin 于 2008-12-16 15:54 编辑 ]

倚楼听风雨,笑看江湖路。。。

TOP

本来就是需要使用replace和正则表达式。
不过这个函数扩展得算是很不错了。

以前我们扩展一般都是只去掉字符串前后的空白。
生命没有假期!
如果生命只剩下最后一秒,你可会想到我?

TOP

TOP

TOP

TOP

TOP

BugMaker!!!!

TOP

学习了
我原来写了一个特别简单的,倒是一直都够用了,呵呵
String.prototype.trim = function(){    var reg = /^\s*(.*?)\s*$/;    return this.replace(reg,"$1");  }

TOP

你们都是吃干饭的吗!!
是!但是俺们也喝稀饭!!

TOP

返回列表