Tags

, , , , ,

Is a certain thing that all Javascript developers need to perform some operations on string variable. Most part of them prefer to add method to String object (for example “String.prototype.trim = function () {}”). There is nothing wrong with it, but problems appear when you need to work on a code developed by someone else and you do not know how he/she wrote extensions methods.

I would prefer a different approach. I would create a namespace “Utils” and add a class called “String” inside this namespace. This way, you can be almost sure you do not interact with methods added directly to global String object. With a little help from MicrosoftAjax.js, this will be simple to achieve.

Type.registerNamespace("Utils");
Utils.String = function () { }
Utils.String.contains = function Utils$String$contains(str, substr, caseSensitive) { }
Utils.String.endsWith = function Utils$String$endsWith(str, suffix, caseSensitive) { }
Utils.String.beginsWith = function Utils$String$beginsWith(str, prefix, caseSensitive) { }
Utils.String.extractFirstChars = function Utils$String$extractFirstChars(str, noOfchars, displayAfterExceed) { }
Utils.String.extractLastChars = function Utils$String$extractLastChars(str, noOfchars, displayAfterExceed) { }
Utils.String.registerClass("Utils.String");

Methods are static and can be called without instantiate “Utils.String” class. For example, checking is a string contains a substring, usage should be very simple.

var textString = "People";
var textSubstring = "peo";
alert(Utils.String.contains(textString, textSubstring , false));

For methods above, you can see implementation here.

/// <Reference Name="MicrosoftAjax.js" />
/// <Reference Name="MicrosoftAjaxWebForms" />
Type.registerNamespace("Utils");

Utils.String = function () { }

Utils.String.contains = function Utils$String$contains(str, substr, caseSensitive) {
    /// <summary>Check if a string contains specified substring</summary>
    /// <param name="str" type="String">String to be checked</param>
    /// <param name="substr" type="String">Substring to be found in source string</param>
    /// <param name="caseSensitive" type="Boolean">Specify if checked will be case sensitive or not</param>
    /// <returns type="Boolean"></returns>
    var e = Function._validateParams(arguments, [{ name: 'str', type: String, mayBeNull: false, optional: false },
                                                    { name: 'substr', type: String, mayBeNull: false, optional: false },
                                                    { name: 'caseSensitive', type: Boolean, mayBeNull: true, optional: true }],
                                                    false);
    if (e) throw Error.create("String contains utility method was called with invalid arguments");

    var _caseSensitive = (typeof (caseSensitive) !== 'boolean') ? false : caseSensitive;
    var _tester = ((_caseSensitive === true) ? (new RegExp(substr, 'g')) : (new RegExp(substr, 'gi')));
    return _tester.test(str);
}

Utils.String.endsWith = function Utils$String$endsWith(str, suffix, caseSensitive) {
    /// <summary>Check if a string ends with a suffix</summary>
    /// <param name="str" type="String">String to be checked</param>
    /// <param name="suffix" type="String">Expected ending text</param>
    /// <param name="caseSensitive" type="Boolean">Specify if checked will be case sensitive or not</param>
    /// <returns type="Boolean"></returns>
    var e = Function._validateParams(arguments, [{ name: 'str', type: String, mayBeNull: false, optional: false },
                                                    { name: 'suffix', type: String, mayBeNull: false, optional: false },
                                                    { name: 'caseSensitive', type: Boolean, mayBeNull: true, optional: true }],
                                                    false);
    if (e) throw Error.create("String endsWith utility method was called with invalid arguments");

    var _caseSensitive = (typeof(caseSensitive) !== 'boolean') ? false : caseSensitive;
    if (_caseSensitive === true) {
        return (this.substr(this.length - suffix.length) === suffix);
    }
    else {
        return (this.substr(this.length - suffix.length).toLowerCase() === suffix.toLowerCase());
    }
}

Utils.String.beginsWith = function Utils$String$beginsWith(str, prefix, caseSensitive) {
    /// <summary>Check if a string ends with a suffix</summary>
    /// <param name="str" type="String" mayBeNull="false" optional="false">String to be checked</param>
    /// <param name="prefix" type="String" mayBeNull="false" optional="false">Expected starting text</param>
    /// <param name="caseSensitive" type="Boolean" mayBeNull="true" optional="true">Specify if checked will be case sensitive or not</param>
    /// <returns type="Boolean"></returns>
    var e = Function._validateParams(arguments, [{ name: 'str', type: String, mayBeNull: false, optional: false },
                                                    { name: 'prefix', type: String, mayBeNull: false, optional: false },
                                                    { name: 'caseSensitive', type: Boolean, optional: true, mayBeNull: true }],
                                                    false);
    if (e) throw Error.create("String beginsWith utility method was called with invalid arguments");
    var _caseSensitive = (typeof (caseSensitive) !== 'boolean') ? false : caseSensitive;

    if (_caseSensitive === true) {
        return (this.substr(0, prefix.length) === prefix);
    }
    else {
        return (this.substr(0, prefix.length).toLowerCase() === prefix.toLowerCase());
    }
}

Utils.String.extractFirstChars = function Utils$String$extractFirstChars(str, noOfchars, displayAfterExceed) {
    /// <summary>Extract specified number of characters from the begining of a string</summary>
    /// <param name="str" type="String">Source string variable for characters extraction</param>
    /// <param name="noOfchars" type="Number">Number of characters to extract</param>
    /// <param name="displayAfterExceed" type="String">Display after extracted string if source exceeds noOfchars</param>
    /// <returns type="String"></returns>
    var e = Function._validateParams(arguments, [{ name: 'str', type: String, mayBeNull: false, optional: false },
                                                 { name: 'noOfchars', type: Number, integer: true, mayBeNull: false, optional: false },
                                                 { name: 'displayAfterExceed', type: String, mayBeNull: true, optional: true }],
                                                 false);
    if (e) throw Error.create("String extracFirstChars utility method was called with invalid arguments");

    var _displayAfter = ((typeof (displayAfterExceed) === "undefined") || (displayAfterExceed === null) || (displayAfterExceed === undefined)) ? ("") : (displayAfterExceed);
    var _str = "";
    for (var i = 0; i < noOfchars; i++) {
        _str += str.charAt(i);
    }


    return _str + ((str.length >   noOfchars) ? (_displayAfter) : (""));
}

Utils.String.extractLastChars = function Utils$String$extractLastChars(str, noOfchars, displayAfterExceed) {
    /// <summary>Check if a string ends with a suffix</summary>
    /// <param name="str" type="String">Source string variable for characters extraction</param>
    /// <param name="noOfchars" type="Number">Number of characters to extract</param>
    /// <param name="displayAfterExceed" type="String">Display after extracted string if source exceeds noOfchars</param>
    var e = Function._validateParams(arguments, [{ name: 'str', type: String, mayBeNull: false, optional: false },
                                                 { name: 'noOfchars', type: Number, integer: true, mayBeNull: false, optional: false },
                                                 { name: 'displayAfterExceed', type: String, mayBeNull: true, optional: true }],
                                                 false);
    if (e) throw Error.create("String extractLastChars utility method was called with invalid arguments");
    if (noOfchars > str.length) return str;


    var _displayAfter = ((typeof (displayAfterExceed) === "undefined") || (displayAfterExceed === null) || (displayAfterExceed === undefined)) ? ("") : (displayAfterExceed);
    var _str = "";
    for (var i = noOfchars + 1; i < str.length; i++) {
        _str += str.charAt(i);
    }
    return  _displayAfter + _str;
}

Utils.String.registerClass("Utils.String");

Advertisements