Sunday, 19 April 2015

JavaScript String

Most of this information is available on the net. I have compiled into a single document for easy reading.

JavaScript code is after the descriptions.

Regular Expression

var enum = StringUtilities.enumRegExpression;

  • var reg = enum.AlphaNumeric

 

Is Empty

var isEmpty = StringUtilities.isEmpty(s);
returns true/false

 

Characters Occur In

var isOk = StringUtilities.charsOccurIn(s, universe);
returns true/false

  • s: string
  • universe: legit characters
  • returns false if any character in "s" is not in "universe"

 

Is Valid AlphaNumeric Characters

var isOk = StringUtilities.isValidAlphaNumericCharacters(s);
returns true/false

 

Left Padding

var mystring = StringUtilities.leftPad(val, size, ch);

  • val: string to add padding to
  • size: size of the resulting string
  • ch: characters that will be used for padding

 

Right Padding

var mystring = StringUtilities.rightPad(val, size, ch);

  • val: string to add padding to
  • size: size of the resulting string
  • ch: characters that will be used for padding

 

Wrap String

var mystring = StringUtilities.wrap(s, n, lineBreak);

  • s: string to add wrap to
  • n: number of characters after which wrapping will be added
  • lineBreak: charctera that will be used for wrapping, usually it is '<br/>'

 

Escape

var mystring = StringUtilities.escape(string);

 

Strip

var mystring = StringUtilities.strip(s, cKeep);
Search through string's characters one by one, add to new string if keep list.

  • s: string to check
  • cKeep: characters to keep, the rest will be removed from 's'

 

Make First Char Upper

var mystring = StringUtilities.makeFirstCharUpper(string);

 

Remove Specific First Char

var mystring.StringUtilities.removeSpecifiedFirstChar(s, cRemove);

 

Is Valid URL

var isUrl = StringUtilities.isValidURL(url);
returns true/false

 

Is Email

var isEmail = StringUtilities.isEmail(email);
returns true/false

 

Is Email Check With Details

This is very powerful method that either gives the specific error number or message. 0 or empty string means email is good.
We can also specifiy TLD -- 2 char domains
var email = StringItilities.isEmailDetail(emailToCheck, blnCheckTLD, blnDetailError);

  • emailToCheck: email to check
  • blnCheckTLD: true will check for 2 char domain otherwise 3 char domain
  • blnDetailError: true will return numeric code, false will return message
code/message translation

number = error string
**********************************************************************************************
0 = empty string -- this means ok
1 = Email address not specified! -- empty string passed for the email address
2 = Email address seems incorrect (check @ and .'s)
3 = Email address username contains invalid characters.
4 = Email address domain name contains invalid characters.
5 = Email address username doesn't seem to be valid.
6 = Email address destination IP address is invalid! -- if we have IP for the domain part
7 = Email address domain name does not seem to be valid.
8 = Email address must end in a well-known domain or two letter country.
9 = Email address is missing a hostname!

StringUtilities.js

var StringUtilities = {
    enumRegExpression: {
        AlphaNumeric: /^[0-9a-zA-Z]+$/
    },
    isEmpty: function (s) {
        return ((s == null) || (s.length == 0));
    },
    charsOccurIn: function (s, universe) {
        // Search through string's characters one by one.
        // Verify that character is in universe.
        for (var i = 0; i < s.length; i++) {
            // Check that current character is in universe
            var c = s.charAt(i);
            if (universe.indexOf(c) == -1)
                return false;
        }
        return true;
    },
    isValidAlphaNumericCharacters: function (item) {
        var expression = StringUtilities.enumRegExpression.AlphaNumeric;
        //alert(StringUtilities.enumRegExpression.AlphaNumeric + " " +item + " " + expression.test(item));
        return expression.test(item);
    },
    leftPad: function (val, size, ch) {
        var result = String(val);
        if (ch == null) {
            ch = " ";
        }
        while (result.length < size) {
            result = ch + result;
        }
        return result;
    },
    rightPad: function (val, size, ch) {
        var result = String(val);
        if (ch == null) {
            ch = " ";
        }
        if (size > result.length) {
            for (var i = result.length; i <= size; i++)
                result += ch;
        }
        return result;
    },
    wrap: function (s, n, lineBreak) {
        //wrap test to second row after cetain number of characters
        //link break can be <br> or \n
        var strReturn = '';
        var s = String(s);
        if (s != '' && s.length > n) {
            while (s != '') {
                strReturn += s.slice(0, n) + lineBreak;
                s = s.slice(n, s.length);
            }
        }
        else
            strReturn = s;
        return strReturn;
    },
    escape: function (string) {
        return string.replace(/('|\\)/g, "\\$1");
    },
    strip: function (s, cKeep) { //Search through string's characters one by one, add to new string if keep list.
        var s = String(s);
        var cKeep = String(cKeep);
        // Is s empty?
        if (string.isEmpty(s)) return "";
        var cNew = new String("");
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (cKeep.indexOf(c) != -1)
                cNew += c;
        }
        return cNew;
    },
    makeFirstCharUpper: function (s) {
        var strReturn = '';
        s = '' + s;
        strReturn = s.charAt(0);
        strReturn = strReturn.toUpperCase();
        strReturn += s.slice(1, s.length);
        return strReturn;
    },
    removeSpecifiedFirstChar: function (s, cRemove) {
        var cReturn = '';
        if (s.length == 1) {
            if (s.toUpperCase() == cRemove.toUpperCase()) cReturn = '';
            else cReturn = s;
        }
        else if (s.length > 1) {
            cReturn = s.charAt(0);
            if (cReturn.toUpperCase() == cRemove.toUpperCase()) cReturn = s.slice(1, s.length);
            else cReturn = s;
        }
        return cReturn;
    },
    isValidURL: function (url) {
        //var expression = /^[a-zA-Z0-9\-\.]+\.(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)?$\/i/;

        //(http|https|ftp)\://
        var expression = new RegExp("^([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$");

        return (expression.test(url.toLowerCase()));
    },
    isEmail: function (emailToCheck) {
        var objPattern1 = /(@.*@)|(\\.\\.)|(@\\.)|(^\\.)/;
        var objPattern2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
        return (!objPattern1.test(emailToCheck) && objPattern2.test(emailToCheck));
    },
    isEmailDetail: function (emailToCheck, blnCheckTLD, blnDetailError) {
        /*
        the function either returns the error number, in this case 0 is no error
        or returns a detailed error string, in this case empty string is no error.
        to get error string, pass true for blnDetailError
       
        to check for if the address ends in a two-letter country or well-known
        TLD, pass blnCheckTLD as true,  true means check, false means do not check
       
        number    =        error string
        **********************************************************************************************
        0        =         empty string                                        -- this means ok
        1        =        Email address not specified!                        -- empty string passed for the email address
        2        =         Email address seems incorrect (check @ and .'s)
        3        =         Email address username contains invalid characters.
        4        =        Email address domain name contains invalid characters.
        5        =         Email address username doesn't seem to be valid.
        6        =        Email address destination IP address is invalid!    -- if we have IP for the domain part
        7        =         Email address domain name does not seem to be valid.
        8        =        Email address must end in a well-known domain or two letter country.
        9        =         Email address is missing a hostname!
        */

        //make sure that the email is lower case
        emailToCheck = emailToCheck.toLowerCase();

        if (blnCheckTLD == 'undefined' || blnCheckTLD == null || blnCheckTLD == '') blnCheckTLD = false;
        if (blnDetailError == 'undefined' || blnDetailError == null || blnDetailError == '') blnDetailError = false;
        if (emailToCheck == 'undefined' || emailToCheck == null) emailToCheck = '';

        //if email to check is blank, return error immediately
        if (emailToCheck == '') {
            if (blnDetailError) return 'Email address not specified';
            else return 1;
        }

        /* The following is the list of known TLDs that an e-mail address must end with. */
        var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

        /* The following pattern is used to check if the entered e-mail address
        fits the user@domain format.  It also is used to separate the username
        from the domain. */
        var emailPat = /^(.+)@(.+)$/;

        /* The following string represents the pattern for matching all special
        characters.  We don't want to allow special characters in the address.
        These characters include ( ) < > @ , ; ~ ` ! # $ % \ ^ & * = } { ' | ? / : \ " . [ ] */
        var specialChars = "\\(\\)><@,;~`!#$%\^&*=}{'|?/:\\\\\\\"\\.\\[\\]";

        /* The following string represents the range of characters allowed in a
        username or domainname.  It really states which chars aren't allowed.*/
        var validChars = "\[^\\s" + specialChars + "\]";

        /* The following pattern applies if the "user" is a quoted string (in
        which case, there are no rules about which characters are allowed
        and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
        is a legal e-mail address. */
        var quotedUser = "(\"[^\"]*\")";

        /* The following pattern applies for domains that are IP addresses,
        rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
        e-mail address. NOTE: The square brackets are required. */
        var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

        /* The following string represents an atom (basically a series of non-special characters.) */
        var atom = validChars + '+';

        /* The following string represents one word in the typical username.
        For example, in john.doe@somewhere.com, john and doe are words.
        Basically, a word is either an atom or quoted string. */
        var word = "(" + atom + "|" + quotedUser + ")";

        // The following pattern describes the structure of the user
        var userPat = new RegExp("^" + word + "(\\." + word + ")*$");

        /* The following pattern describes the structure of a normal symbolic
        domain, as opposed to ipDomainPat, shown above. */
        var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

        /* Finally, let's start trying to figure out if the supplied address is valid. */

        /* Begin with the coarse pattern to simply break up user@domain into
        different pieces that are easy to analyze. */
        var matchArray = emailToCheck.match(emailPat);

        if (matchArray == null) {
            /* Too many/few @'s or something; basically, this address doesn't
            even fit the general mould of a valid e-mail address. */
            if (blnDetailError) return "Email address seems incorrect (check @ and .'s)";
            else return 2;
        }
        var user = matchArray[1];
        var domain = matchArray[2];

        // Start by checking that only basic ASCII characters are in the strings (0-127).
        for (i = 0; i < user.length; i++) {
            if (user.charCodeAt(i) > 127) {
                if (blnDetailError) return "Email address username contains invalid characters.";
                else return 3;
            }
        }
        for (i = 0; i < domain.length; i++) {
            if (domain.charCodeAt(i) > 127) {
                if (blnDetailError) return "Email address domain name contains invalid characters.";
                else return 4;
            }
        }

        // See if "user" is valid
        if (user.match(userPat) == null) {
            if (blnDetailError) return "Email address username doesn't seem to be valid.";
            else return 5;
        }

        /* if the e-mail address is at an IP address (not host name)
        make sure the IP address is valid. */
        var IPArray = domain.match(ipDomainPat);
        if (IPArray != null) { //We have ourselves an IP address for email address
            for (var i = 1; i <= 4; i++) {
                if (IPArray[i] > 255) {
                    if (blnDetailError) return "Email address destination IP address is invalid!";
                    else return 6;
                }
            }
            //this is valid IP address
            if (blnDetailError) return "";
            else return 0;
        }

        // See if "domain" is valid
        var atomPat = new RegExp("^" + atom + "$");
        var domArr = domain.split(".");
        var len = domArr.length;
        for (i = 0; i < len; i++) {
            if (domArr[i].search(atomPat) == -1) {
                if (blnDetailError) return "Email address domain name does not seem to be valid.";
                else return 7;
            }
        }

        /* domain name seems valid, but now make sure that it ends in a
        known top-level domain (like com, edu, gov) or a two-letter word,
        representing country (uk, nl), and that there's a hostname preceding
        the domain or country. */
        if (blnCheckTLD && domArr[domArr.length - 1].length != 2 &&
                domArr[domArr.length - 1].search(knownDomsPat) == -1) {
            if (blnDetailError) return "Email address must end in a well-known domain or two letter country.";
            else return 8;
        }

        // Make sure there's a host name preceding the domain.
        if (len < 2) {
            if (blnDetailError) return "Email address is missing a hostname!";
            else return 9;
        }

        // If we've gotten this far, everything's valid!
        if (blnDetailError) return '';
        else return 0;
    }
};