Tutorial details
Name : String Array
Author : Kenneth Clark
Language : JavaScript
Platform : Platform Independant
Click here if you require development or hosting solutions : [ SkyeTech Solutions ]

When recently fiddling with a rewrite rule I wrote a very funny piece of PHP.

On further testing of the code I realise (which probably should have been obvious) that PHP treats a string as an array (very much the same as C++, C# and the likes). Okay nothing new I know but bare with me here.

While perusing a forum that I participate in someone requested a way to count the occurance of a unique character inside a JavaScript string. So I decided to test the string array theroy in JavaScript.

Just a quick primer for those that don't know what I am talking about. When you assign a string value to a variable something like.

//we will use php as it is easy to illustrate with.
$str = "Hello World";
Okay now the $str variable is actually an array of characters something like
$str[0] = "H";
$str[1] = "e";
$str[2] = "l";
$str[3] = "l";
$str[4] = "o";
$str[5] = " ";
$str[6] = "W";
$str[7] = "o";
$str[8] = "r";
$str[9] = "l";
$str[10] = "d";
So if we perform this for loop it will echo the same string
for($i = 0; $i < count($str); $i++){
  echo $str[$i];
}
//once this loop is complete it will read Hello World
Okay now taking that concept and applying it to JavaScript is pretty simple aside from the objects. There is only one major change. PHP has the function "count()" to return the length of an array. In JavaScript array objects have a "length" property.
str = "Hello World";
output = "";
for(i = 0; str.length; i++){
  output += str[i];
}
alert(output);
//this will produce a message box saying Hello World.
Now I hope you are beginning to see where I am going with this and how we can use it to solve the problem of finding the count of unique characters.
str = "#Hello#World#";
findCount = "#";
counter = 0;
for(i = 0; str.length; i++){
  if(str[i] == findCount){
    counter++;
  }
}
alert(findCount + " appeared " + counter + " time(s)");
Another nifty little thing (not that you would ever use it) is to reverse the string.
 str  = "Hello World";
 newLength = str.length - 1;
 reverseString = "";
 for(i = 0; i < str.length; i++){
   reverseString += str[newLength - i]
 }
 alert(reverseString);
Pretty simple once you know how it is broken down right? I am sure there are ways of doing this via a regular expression but I thought it would be nice for people to understand how to manipulate strings.


SkyeTX Technologies Business Software Solutions
SkyeTX Technologies Business Software Solutions