Extending Native String with SliceWord Function

The sliceWord function easily slice out a section of words from a string. This may be useful for form validation, DOM class manipulation, test replacement, and a whole lot more. The method is attached to "String.prototype", but could be easily modified to be standalone. Up to two optional parameters can be applied, where the first parameter is the word index to start (start index) slicing from, and the second parameter is the index of the word to stop slicing at (sliceWord works much like "Array.slice"). If the stop index is not provided, then all words after and including the word at the start index will be returned. If the start index is larger than the number of words in the string, then NULL is returned. However, when no or invalid parameters are provided the string itself is returned, and if the stop index exceeds the number of words in the string, then the method will return the whole string after and including the start index.

Example 1: String.prototype.sliceWord

String.prototype.sliceWord = function(i, j) {
    var args = arguments,
        str =  + this,
        m = 0 < i ? i : 0,
        n = 0 < j ? j : 0,
        _split = str.split();

    // if no args are sent, then return str
    if (args.length) {
        if (_split.length < m) {return;}
        str = (1 < args.length && n < _split.length ? _split.slice(m, n) : _split.slice(m)).join();

    return str;

This method is particularly helpful, when designer use CSS classes to style the markup. Generally, the first class is going to be provided by the designer and it will apply the defaults styles. Additional, classes can be applied by the JavaScript engineer in response to user interactions with the page to change styles. For example, suppose there is an input node with the class button, which also has the class disabled applied to it. By default "input.button" styles make the button look like a standard HTML button, however, when input.button.disabled is applied, the button grays out an looks disabled. The JavaScript adds the disabled class to the button when the form is incomplete, but the button class always removes. Once the form validates the JavaScript needs to remove the disabled class, so we could use the following:

Example 2: dom_removeClasses Function

var dom_removeClasses = function(elem, i) {
    var node = YAHOO.util.Dom.get(elem);
    if (! node) {return;} // safety measure
    node.className = node.className.sliceWord(0, i);
dom_removeClasses(myButton, 1);

Example 2 will remove all classes applied to myButton, except the first one (button). Now, this example is relatively simple, and sliceWord is probably overkill, because we know all the classes applied to button and there are only 2 classes. However, it becomes much more useful when a node can have any combination of 5 classes applied to it.

In the next release of Mint.com we frequently use this technique to normalize elements before applying additional classes to them. This helps to make the JavaScript code less fragile when design makes simple class changes or when they forget to remove classes from the views.

Get Common Ancestor Function

One way to improve the dispatch technique from last week is to only attach the single listener to the greatest common ancestor of all elements that we are dispatching. To achieve this, the following method to find the common ancestor of two elements was needed:

Example 1: Get Common Ancestor Function

YAHOO.util.Dom.getCommonAncestor = function(elem1, elem2) { var node1 = YAHOO.util.Dom.get(elem1), node2 = YAHOO.util.Dom.get(elem2); if (! (node1 && node2)) {return null;} // missing parameter, fail ...

Extending Native Boolean

There is very little you need to attach to Boolean, as it is a very simple object. I have only found two methods that I like to attach to the Boolean Object: is and get. The is method is a type detection like I have attached to other native JavaScript objects. The get method is to convert falsy/truthy values into false and true. While this isnt necessary because you can use "! yourObject", however I ...

Augmenting Native Object Continued (Part II)

While it is always best practice to never extend the prototype of Object, it is fine to extend Object directly with your own static methods. There are 4 methods that I find critical to working with JavaScript objects: forEach, getIgnoreKeys, is, and toQueryString. The forEach method iterates on the Object using the "for … in" loop, but calls getIgnoreKeys to determine which keys are methods attached to the Object prototype, and ignores those values. You ...

Extending Native Array

I have not written code extending Array yet, as I have had concerns about breaking the web while extending Array. The problem is that any changes to the prototype of Array breaks "for … in" loops. After some discussion with other JavaScript architects and further thought, it became apparent that extending Array doesnt really break the web. First of all, the only issue is that after modifying the "Array.prototype", using "for … in" loops on ...

Extending Native String Continued (Part II)

In the past, I wrote an article extending the native JavaScript String Object with useful methods and also about a RegExp escape method: String FunctionsRegExp Escape I have revisited those methods and also added several other methods to String.prototype and static methods to String that I find useful. Check out the new String.js here and the unit test here if you want to double check that it all works well ...

Exnteidng Native Number

4 months ago, I wrote an article extending the native JavaScript Number Object with a format method: Numbers and Number Format Function I have revisited that method and also added several other methods to Number.prototype and Number that I find useful. Check out the new Number.js here and the unit test here if you want to double check that it all works well on your favorite browser. Mostly, there is the format ...

Extending Native Date Continued (Part II)

About 6 months ago, I wrote several articles about extending the native JavaScript Date Object with constants, static methods, and public methods on the prototype: Date FunctionsYUI Datemath on JavaScript Date Object The first article describes methods that I designed myself, while the second explains how to convert YUI Datemath to extend the Date Object instead of using static methods. I recently revisited all the methods that I append to Date and ...

Escaping RegExp Characters Function

If you use regular expressions on your site, then I am sure you have encountered situations where you use a String value, possibly returned from the some user input, as part of your regular expressions. The syntax you might use:

Example 1: Typical Syntax

var haystack = Hello World, my name is NAME!; var needle = NAME; var rx = new RegExp(needle); alert(haystack.replace(rx, Matt Snider)); 
This very simple example shows how you create ...

Dom.Activate to Focus on Form Elements

One of the methods that I missed when switching from Prototype to YUI, was a generic method to use to focus on a form element and/or selecting its text. Each browser supports focus in a slightly different way and until recently most did not support the select Function on an Input Element. In addition, you should never attempt to focus on a hidden or non-displayed Element, nor should you focus on an Input Element of ...