String Object

JavaScript topics covered:
  1. Concatinate:

    When one object you are adding is a string, then the items are concatinated together. For example when adding two strings, they are concatinated.

    stuff = "this is some stuff";
    moreStuff = " here is more stuff";
    answer = stuff + moreStuff // answer = "this is some stuff here is more stuff"
    

    The same is true if one object is a string and the other a number. The two will be concatinated.

    item = "The number of tennis balls I have :";
    count=3;
    answer = item+count		//answer = "The number of tennis balls I have :3"
    
  2. Convert to a string

    Sometimes you want to perform string methods on a number or a date. Before you can do that you need to convert the number to a string, otherwise you will get javaScript error. In the following function I wanted to split the dollars from the cents at the decimal place. Using the split method of the string object works great, however first you have to convert the number to a string.

    function fix(numToFix, decimalPlaces){
    if(isNaN(fixNumber)) 	return 0;
    var div = Math.pow(10, decimalPlaces);	
    numToFix = Math.round(numToFix * div)/div;	
    var string = numToFix.toString();	//convert the number to a string variable
    	var parts = string.split(".");	//split at the decimal
    	var cents = parts[1];		//(dollars in one part,cents in the other)
    	while (cents.length<decimalPlaces)	//add as many zeros as needed
    	     cents += "0";
    	return parts[0]+"."+cents	//return the formatted number
    }
    click here to see the demo
  3. Sting Methods

    Sting methods that change the style:


    Find the position within the string of a word or character.
    substring and indexOf are used quite a bit with cookies.


    str.replace(regexp, replacement) - replace substring(s) matching a regular expression
    
    var str="Visit Microsoft!"
    document.write(str.replace(/Microsoft/,"Techinmotion"))
    

    str.split(delimiter, limit)   - Splits a string at the delimiter into an array of strings
    
    arrShipTo = strShipTo.split("~"); //splits strShipTo at each "~" into an array arrShipTo
    

    click here for a complete list of string methods



  4. Practical Examples