Javascript: Converting a variable string name to a readable form

I build this one on a project where-in i have a lot of input types, and i’m a bit lazy to manually type it’s readable form, so i created a function wherein it will automatically converts a variable name or string to its readable form. This javascript function has some rules in mind:

  • naming convesion: the first 3 letters of the string specifies its element type (e.g “txt” for a “text” type, “ddl” for a dropdown list). regardless of types, the starting 3 letters is ignored.
  • Camel casing – the string should be in a form of camel casing since it relies that the first capital letter or number it found means a new word.
  • numeric is considered a new “word” (e.g txtNameOfSibling1, will result in “Name Of Sibling 1”

Sample usage:

ToProperWord("txtNameOfSibling1");
Result: ” Name Of Sibling 1″

so here’s the code snippet. let me know your thoughts.

	function ToReadableForm(ElementName)
	{
		var toConvert = ElementName;
		if(toConvert.length > 3)
		{
			var converted = toConvert.substring(3, toConvert.lenght);
			var buildWord = "";
			var finalWord = "";
			var ucaseCtr = 0;
			for(var ctr = 0; ctr < converted.length; ctr++)
			{
				var newWord = false;				
				var curChar = converted.charAt(ctr);
				if(curChar == curChar.toUpperCase() || !isNaN(curChar)) { newWord = true; }								
				if(buildWord != "" || newWord == true)
				{
					if(newWord == true)
					{
						finalWord = finalWord + " " + buildWord;
						buildWord = "";
					}
					buildWord = buildWord + curChar;				
				}
			}
			finalWord = finalWord + " " + buildWord;
		}		
		return finalWord;
	}
Advertisements