Tuesday, June 10, 2008

JavaScript endsWith() and trim()

Today I needed a new JavaScript string function to see if the end of a string matched something. In ASP.NET, when controls within other controls get written as HTML, the id's get prepended with a bunch of junk from the container controls. So, for your JavaScript functions to find a particular control, it's useful to use document.getElementsByTagName('input') for example to get a list of input tags, then iterate the list testing the end of the id attribute to find a particular control. Anyway, I used 'prototype' to add an endsWith(x) function to strings. Here it is. I hope you find it useful.
String.prototype.endsWith = function(txt,ignoreCase)
{
  var rgx;

  if(ignoreCase)
  {
    rgx = new RegExp(txt+"$","i");
  }
  else
  {
    rgx = new RegExp(txt+"$");
  }

  return this.match(rgx)!=null; 
}

For example: 'hello'.endsWith('LO',true) returns true. Notice I passed in a true value for the ignoreCase parameter. Or with a variable: var x = 'goodbye'; then x.endsWith('bye') returns true. While I'm here, here's a cool one liner that will do a trim() on both sides of a string.
String.prototype.trim = function()
{
  return this.replace(/(^\s*|\s*$)/g,'');
}
For example: alert('.' + '    blah    '.trim() + '.'); shows ".blah."

0 comments: