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:
- As Javascript is used in nearly every web-related project, you're bound to reuse this library over and over again.
- 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?