Category Archives: JavaScript

String.protototype.toCharCodes()

One of the functions that didn’t make the cut for jPaq is String.prototype.toCharCodes().  The reason is I don’t feel that it is a function that many people are looking for.  Still, if you are looking for a good implementation for it, you can use this:

String.prototype.toCharCodes = function() {
  for(var arr = this.split(""), i = this.length - 1; i >= 0; i--)
    arr[i] = arr[i].charCodeAt(0);
  return arr;
};

From Wildcards To Regular Expressions

There are a lot of people out there that no how to do file searches and Microsoft Word searches by using wildcard characters, but not as many people know how to work with regular expressions. That is the main reason why I added the RegExp.fromWildExp() function to jPaq. In addition, I have created an example page which dynamically generates the regular expression from the wildcard expression that you specify. Check this jPaq example out by clicking here.  The initial example shows you how to write a regular expression that matches all text that starts at the beginning of a word with a capital “J” and ends at the end of a word with a lowercase “t”.  NOTE:  Unlike regular expressions, wildcard expressions look to find the smallest match possible.

getMatches(str, exp)

I recently encountered two troubling bugs with jPaq’s String.prototype.indexOfPattern() function.  In order to fix it, I ended up exploring the powerful String.prototype.replace() function, exploiting the parameter passed into the callback function.  I already knew that the matched text and sub-groups were passed into the callback function.  The thing that I didn’t know was that the second-to-the-last parameter passed is the start index of the matched string.  This gave me the idea to create a function which can return an array of all of the matches and sub-groups in object literals, along with the offset and original text.  Instead of me explaining it, take a look:

function getMatches(str, exp) {
  var ret = [];
  str.replace(exp, function() {
    var match = {length : arguments.length - 2};
    for(var i = 0, iOffset = match.length; i < iOffset; i++)
      match[i] = arguments[i];
    match.offset = arguments[i];
    match.original = arguments[i + 1];
    ret.push(match);
  });
  return ret;
}