Digital Serenity

Digital Serenity is the blog of John McPherson Leask III (Jay). His mind wanders from food to travels, every-day activities and humor to sports, podcasting and technology - though mostly the focus of Digital Serenity will be his technological exploits.

Javascript Library: getSubString()

Every web developer, even those in denial that they are such, should have a solid library of JavaScript functions that they can bring with them to every project. The reasons are many, but lets just start with the following two today:

  1. As Javascript is used in nearly every web-related project, you're bound to reuse this library over and over again.
  2. You have enough to code - don't waste your time redoing this every time you take on another project.

So today I offer you a simple custom Javascript to extend the use of the Javascript substring() method. Why the substring method? How often have you found yourself needing the middle of a string (can anyone say query string values?).

getSubString()
function getSubString(thestring, pointFrom, pointTo)
{
  if (pointFrom != null && pointFrom != '')
  {
    var start = thestring.indexOf(pointFrom) + pointFrom.length;
    var secondString = thestring.substring(start, thestring.length);
  } else {
    var secondString = thestring;
  }
  var end = secondString.indexOf(pointTo);
  if (pointTo != '' && end >= 0) {
    var finalString = secondString.substring(0, end);
  } else {
    var finalString = secondString;
  }
  return finalString;
}

As I've said, it's a fairly simple function. there are three parameters:

  • thestring
    The string you are looking to substring from.
  • pointFrom
    The starting point within your string; passing a null value will start your substring from the beginning.
  • pointTo
    The ending point within your string; passing a null value will use the end of the original string as your ending point.

This is the version I use, any suggestions?

Published Sunday, May 13, 2007 5:11 PM by jleask
Filed under: ,

Comments

No Comments