Make a split function like Ruby's: "abc".split(/b/) -> ['a', 'b', 'c'] - Node.js String

Node.js examples for String:Split

Description

Make a split function like Ruby's: "abc".split(/b/) -> ['a', 'b', 'c']

Demo Code


/*--------------------------------------------------------------------------
 *  MVC.View - Embedded JavaScript, version 0.1.0
 *  Copyright (c) 2007 Edward Benson/*from   ww w  .j  a v  a 2 s  . c o  m*/
 *  http://www.edwardbenson.com/projects/MVC.View
 *  ------------------------------------------------------------------------
 *
 *  EJS is freely distributable under the terms of an MIT-style license.
 *
 *  EJS is a client-side preprocessing engine written in and for JavaScript.
 *  If you have used PHP, ASP, JSP, or ERB then you get the idea: code embedded
 *  in <% // Code here %> tags will be executed, and code embedded in <%= .. %> 
 *  tags will be evaluated and appended to the output. 
 * 
 *  This is essentially a direct JavaScript port of Masatoshi Seki's erb.rb 
 *  from the Ruby Core, though it contains a subset of ERB's functionality. 
 * 
 * 
 *  For a demo:      see demo.html
 *  For the license: see license.txt
 *
 *--------------------------------------------------------------------------*/

/* Make a split function like Ruby's: "abc".split(/b/) -> ['a', 'b', 'c'] */
String.prototype.rsplit = function(regex) {
  var item = this;
  var result = regex.exec(item);
  var retArr = new Array();
  while (result != null)
  {
    var first_idx = result.index;
    var last_idx = regex.lastIndex;
    if ((first_idx) != 0)
    {
      var first_bit = item.substring(0,first_idx);
      retArr.push(item.substring(0,first_idx));
      item = item.slice(first_idx);
    }    
    retArr.push(result[0]);
    item = item.slice(result[0].length);
    result = regex.exec(item);  
  }
  if (! item == '')
  {
    retArr.push(item);
  }
  return retArr;
};

/* Chop is nice to have too */
String.prototype.chop = function() {
  return this.substr(0, this.length - 1);
};

Related Tutorials