Ruby's Louvre

每天学习一点点算法

导航

rsplit函数

类似split函数,但保留切割符。

var rsplit = function( string, regex ) {
          var result = regex.exec(string),
          retArr = [],
          first_idx, last_idx;
          while ( result !== null ) {
            first_idx = result.index;
            last_idx = regex.lastIndex;
            if ( first_idx !== 0 ) {
              retArr.push(string.substring(0, first_idx));
              string = string.slice(first_idx);
            }
            retArr.push(result[0]);
            string = string.slice(result[0].length);
            result = regex.exec(string);
          }
          if ( string !== '' ) {
            retArr.push(string);
          }
          return retArr;
        };

var rsplit = function(str,reg){
    var result = [], i =0 ,left;
     while(reg.exec(str)){
           left = RegExp.leftContext;
           if(left){
              result[i++] = left;
           }
           result[i++] = RegExp.lastMatch;
           str = RegExp.rightContext;
     }
     if(str){
        result[i++] = str
     }
       return result;
}

用法:

 var  name = 'example.projectrepo.pkg2'
 alert(rsplit(name,/\./g)) //example,.,projectrepo,.,pkg2

posted on 2010-08-14 09:22  司徒正美  阅读(2319)  评论(0编辑  收藏  举报