Javascript Gettok

By sean on May 03, 2012

Thought it would be a neat exercise to recreate the mIRC $gettok() function in javascript as I've seen it popup in several other languages. The only caveat I'm aware of is when passing multiple N parameters (eg: '2-6' or '2-'); it must be in string format. Otherwise javascript will interpret N and pass undesired results (eg: '-4'). If only passing one N parameter, integer use is recommended.

var s = 'this is sparta yo rawr meow woof moo', r;
r = gettok(s, '2-6', 32); // result: is sparta yo rawr meow
r = gettok(s, 2, 32); // result: is
r = gettok(s, '6-', 32); // result: meow woof moo
function gettok(s, n, c) {
  var c = String.fromCharCode(c), sa = s.split(c);
  if (!/-/.test(n)) {
    n = (n - 1);
    return sa[n] || NaN;
  } else {
    n = n.split('-'), o = [];
    var x = n[1] || s.length;
    for (var i = (n[0] - 1); i < x; i++) o.push(sa[i]);
    return (o.length > 0) ? o.join(c) : NaN;
  }
}

Comments

Sign in to comment.
Hawkee   -  May 03, 2012

Neat.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.