split vs regex vs indexOf to extract value from path or URL (v2)

Revision 2 of this benchmark created by DaveInOhio on


Description

Extract the value from a path or URL that follows a token, where the token search is case insensitive. Note that function getValueSplit() would return the desired value in lowercase, which, though acceptable in my application, may not always be desirable. Conversely, getValueRegex() and getValueIndexOf() return the desired value as entered.

Setup

var hrefs = [
      'http://example.com/subsite/keYword/keyVALUe1',
      'http://example.com/subsite/keywoRd/keyvalue2/',
      'http://example.com/subsite/keyword/kEYVvalue3/more',
      'http://example.com/subsite/nokeyword/nokeyvalue/more',
      'http://example.com/subsite/keyword/',
      'http://example.com/subsite/keyword',
      'http://example.com/subsite/more'
    ];
    var token = 'keyword';
    
    function getTheValues(f) {
      var value;
      for (var i = 0; i < hrefs.length; i += 1) {
        value = f(hrefs[i]);
        alert(value);
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
split test
var getValueSplit = function(h) {
  var a, idx, val;
  a = h.toLowerCase().split('/');
  idx = a.indexOf(token);
  val = (idx > -1 && idx < a.length - 1) ? a[idx + 1] : 'none';
  return ('' !== val) ? val : 'none';
};

getTheValues(getValueSplit);
ready
regex test
var reg = new RegExp("/" + token + "/([^/]+)/?", "i");

var getValueRegex = function(h) {
  var a = reg.exec(h);
  return (null !== a) ? a[1] : 'none';
};

getTheValues(getValueRegex);
ready
indexOf test
var getValueIndexOf = function(h) {
  var start = h.toLowerCase().indexOf('/' + token + '/');
  if (-1 === start) {
    return 'none';
  }
  start += token.length + 2;
  if (h.length < start + 2) {
    return 'none';
  }
  var end = h.indexOf('/', start + 1);
  end = (-1 === end) ? h.length : end;
  return (end > start) ? h.substring(start, end) : 'none';
};

getTheValues(getValueIndexOf);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by DaveInOhio on
  • Revision 2: published by DaveInOhio on
  • Revision 3: published on