Wednesday, November 14, 2007

Useful Prototype.js String Functions

Often while doing web development with JavaScript there is a need to do some kind of string manipulation. Some of the more common tasks are checking if the string is empty and replacing some parts of the string but it doesn't have to stop there. Sometimes I want to capitalize the first letter in a string or check if the string ends with a certain character. In the past I would have to write functions most often involving regular expressions to do each of those trivial tasks. Luckily, in the present my favorite JavaScript library Prototype.js already comes with the mentioned above plus a bunch more string functions. Here are some that I use often:

  • empty() - checks if a string is empty
    var myEmptyString = "";
    if (myEmptyString.empty()) alert ('myEmptyString is empty');
  • blank() - checks if a string is either empty or contains white space
    var myBlankString = " ";
    if (myBlankString.blank()) alert ('myBlankString is blank');
  • capitalize() - capitalizes the first letter in a string
    var myString = "lower_case_string";
    // Will show an alert with "Lower_case_string"
  • gsub(pattern, replacement) - replaces a pattern in the string with the string specified in 'replacement'
    var myString = "some_string";
    // Will show an alert with "some string"
    alert(myString.gsub('_', ' '));
  • endsWith(substring) - checks if the specified string ends with the provided 'substring'
    var myString = "some string_";
    // Will show an alert with "myString ends with _"
    if (myString.endsWith('_')) alert('myString ends with _');
Many more can be found at the Prototype API reference
// //]]>