JavaScript Propercase function

This function is the JavaScript equivalent to the notes @ProperCase (or as near as I can make it).

You need two routines: split() and toPC(). This function is the JavaScript equivalent to the notes @ProperCase (or as near as I can make it). For example thIs iS NOT proper-case returns This Is Not Proper-Case. You might have to adjust the formating of the code below to get it to work properly. I used tabs to indent each code segment.

Call the routine using newString=toPC(originalString). Note that you should probably strip any apostrophes or extraneous characters first.


//split a string s with the delimeter del
function split(s,del){
	arrS= new Array();
	var i=0;
	var j=0;
	var k=0;
	var delim=new String(del);

	//Is the delimeter in the string
	if(s.indexOf(delim)!=-1){
		for (i=0; i<s.length;i++){
			if(s.charAt(i)==delim){
				if(k==0){
					arrS[j]=s.substring(k,i);
				}else{
					arrS[j]=s.substring(k+1,i);
				}
				k=i;
				j++;
			}
		}
		arrS[j]=s.substring(k+1,s.length);
	}else{
		arrS[0]=s;
	}
	return arrS;
}

//Converts string to ProperCase with spaces and hyphens
function toPC(s){
	var i;
	var returnString = "";
	var tmpS=s.toLowerCase();
	var arrS= new Array();
	var arrS2 = new Array();
	
	//search each word in array arrS
	arrS=split(tmpS," ");
	
	for (i = 0; i < arrS.length; i++){   
		var thisWord=arrS[i];
		//Check to see if word contains a hyphen
		if(thisWord.indexOf("-")!=-1){
			arrS2 = split(thisWord,"-");
			for(var j=0; j < arrS2.length; j++){
				var thisWord2=arrS2[j];
				returnString = returnString + thisWord2.charAt(0).toUpperCase() + thisWord2.substring(1,thisWord2.length)+"-";
				
			}
			returnString = returnString.substring(0,returnString.length-1)+" ";
		} else {
			returnString = returnString + thisWord.charAt(0).toUpperCase() + thisWord.substring(1,thisWord.length)+" ";
		}
	}
	returnString = returnString.substring(0,returnString.length-1);
	
	return returnString;
}
This was first published in February 2002
This Content Component encountered an error

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchWinIT

Search400

  • iSeries tutorials

    Search400.com's tutorials provide in-depth information on the iSeries. Our iSeries tutorials address areas you need to know about...

  • V6R1 upgrade planning checklist

    When upgrading to V6R1, make sure your software will be supported, your programs will function and the correct PTFs have been ...

  • Connecting multiple iSeries systems through DDM

    Working with databases over multiple iSeries systems can be simple when remotely connecting logical partitions with distributed ...

SearchEnterpriseLinux

SearchVirtualDataCentre.co.UK

Close