Home > Javascript > Must Have Functions in JavaScript

Must Have Functions in JavaScript

JavaScript does not comes with pre-bundled functions or methods that can perform special operations. We as a programmer has to write those functions. In this article i am listing down few javascript functions that i have encountered.

Loading XML File in JavaScript:

function load_xml_file(xmlFilePath) {
    if (window.ActiveXObject) {
        //for IE
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.load(xmlFilePath);
        return xmlDoc;
    } else if (document.implementation && document.implementation.createDocument) {
        //for Mozila
        xmlDoc= document.implementation.createDocument("","",null);
        xmlDoc.async=false;
        xmlDoc.load(xmlFilePath);
        return xmlDoc;
    }
}

Loading XML String Content in JavaScript:

function load_xml_string(xmlString) {
     if (window.ActiveXObject) {
         //for IE
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(xmlString);
        return xmlDoc;
      } else if (document.implementation && document.implementation.createDocument) {
         //for Mozila
         parser=new DOMParser();
         xmlDoc=parser.parseFromString(xmlString,"text/xml");
         return xmlDoc;
      }
}

Trim String Content in JavaScript:

function trim(str) {
     var newstr;
     newstr = str.replace(/^\s*/, "").replace(/\s*$/, "");
     newstr = newstr.replace(/\s{2,}/, " ");
     return newstr;
}

Your email:

 


Getting DIV Position in JavaScript:

function getPosition(obj){
    var topValue= 0,leftValue= 0;
    while(obj) {
         leftValue+= obj.offsetLeft;
         topValue+= obj.offsetTop;
         obj= obj.offsetParent;
    }
     finalvalue = leftValue + "," + topValue;
     return finalvalue;
}

Check Whether Entered Value contains Numeric Data:

function IsNumeric(sText){
     var ValidChars = "0123456789";
     var IsNumber=true;
     var Char;
     for (i = 0; i< sText.length; i++) {
        charData = sText.charAt(i);
        if (ValidChars.indexOf(charData) == -1) {
             IsNumber = false;
             break;
        }
     }	
     return IsNumber;
}

Check for Special Character in given Value:

function chkCharacter(data) {
       var success = false;
       var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~"; 
       for (var i = 0; i < data.length; i++) {
            if (iChars.indexOf(data.charAt(i)) != -1) {
                   success = true;
                   break;
            }
        }
        return success;
}

Delete All Rows From Table Except 1st Row:

function clearTable(tableName) {
     var lastRow = document.getElementById(tableName).rows.length;
     if(lastRow > 1) {
           for(i=lastRow-1;i>0;i--) {
                document.getElementById(tableName).deleteRow(i);
           }
     }
}

Convert XML Object To XML String Content:

//Works only in Mozilla Firefox Browser
function xmlToString(xmlObj) {
      return (new XMLSerializer()).serializeToString(xmlObj);
}

String.replaceAll in JavaScript:

     String.prototype.replaceAll = function(pcFrom, pcTo) {
         var i = this.indexOf(pcFrom);
         var c = this;
         while (i > -1) {
             c = c.replace(pcFrom, pcTo);
             i = c.indexOf(pcFrom);
         }
         return c;
      }

Hide DIV / SPAN in JavaScript:

function hideDiv(divObj) {
        document.getElementById(divObj).style.display = "none";
}

Show DIV / SPAN in JavaScript:

function showDiv(divObj) {
       document.getElementById(divObj).style.display = "inline";
}

Check for First Character Entered is Alphabet in JavaScript:

function chkSpecial(content) {
     if (!((content.charAt(0).search(/[a-z]+/)	> -1) || (content.charAt(0).search(/[A-Z]+/)	> -1))){
        alert("Please! enter the name that start with character.");
     }
}

Remove All WhiteSpace Between Words in JavaScript:

function removeWhiteSpace(content) {
    return content.replace(/\s/g, "");
}


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Javascript Tags:
  1. Erol
    December 30th, 2008 at 13:16 | #1

    Check Whether Entered Value contains Numeric Data:
    IsNumeric(‘.’) returns true, but is . (dot) a number?

  2. December 30th, 2008 at 17:45 | #2

    This might simplify things a bit for “Check Whether Entered Value contains Numeric Data”:

    function IsNumeric( s ){
        return /^\d+\.?\d*$/.test( s );
    }
    

  3. December 30th, 2008 at 22:15 | #3

    Hi Brain,
    Thats great with this only developer community will know the power of regular expression instead of traditional approach.

  4. December 30th, 2008 at 22:17 | #4

    Hi Erol,
    I didn’t notice that there was (.) dot inside numeric check. Have remove that. Thank You for Informing the same.

  5. Neil
    December 30th, 2008 at 23:51 | #5

    Um, why not isNaN?

  6. December 31st, 2008 at 08:28 | #6

    Just use a framework (MooTools or Prototype). Most of this is done in a framework.

  7. December 31st, 2008 at 10:43 | #7

    Hi. Nice set of functions. The showDiv() function should probably set the ‘display’ property to ‘block’ rather than ‘inline’, since divs are traditionally block-level elements.

  8. Strx
    January 2nd, 2009 at 02:52 | #8

    With Regexp + jQuery, all of this functions === a single line of code

  9. Harry
    February 3rd, 2009 at 03:23 | #9

    Hi,
    While loadin an xml file into script (1st function), am getting a ‘security error’ at xmlDoc.load(xmlFilePath); statement.. which i suppose is because of the file path… i tried both absolute and relative paths.. can some one pls help me with this.. how should my xmlFileP ath be ?, if i can give just file name, then where would my xml file be located.. ( i may seem dumb here but really need this)…
    i could only see error as ‘security error’ using javascript try-catch (e.message), so not sure of what is the reason for security error
    Appreciate your help here

  1. No trackbacks yet.