PDA

View Full Version : split + joining aarrays



mr bibble
10-28-2005, 03:03 AM
I'm having trouble doing a replace sequence, I want to get rid of the .gif bit of a string using .split then .join
I have an array

myArray = new Array();
myArray[0] = "cheese.gif";
myArray[1] = "another";

Then I create a variable on [0] of myArray

bitOfArray = myArray[0];
bitOfArray.split(".gif")
bitOfArray.join("");
alert(bitOfArray);

all it does is return the original string (with the .gif)



Can anyone help??? :confused:

jscheuer1
10-28-2005, 04:08 AM
bitOfArray.split(".gif")

doesn't change the value of 'bitOfArray', at least as far as I can tell. I take it you want to extract cheese or whatever the filename is without its extension. This worked here in FF, Opera, and IE:


<script type="text/javascript">
myArray = new Array();
myArray[0] = "cheese.gif";
myArray[1] = "another";

bitOfArray = myArray[0].split(".gif");
bitOfArray.length--
alert(bitOfArray);
</script>

Notes: This does not change the value of myArray[0]. You can test this by changing the alert to:


alert('bit='+bitOfArray+' myArrayZero='+myArray[0]);

The line 'bitOfArray.length--' simply removes a comma (,) from the end of the string that the split method inserts.

mwinter
10-28-2005, 12:46 PM
I'm having trouble doing a replace sequence, I want to get rid of the .gif bit of a string using .split then .joinWhy? It's much easier with the String.prototype.replace method, or the substring and lastIndexOf methods:



var string = 'cheese.gif';

string = string.replace(/\.[^.]*$/, '');

/* or:
*
* var i = string.lastIndexOf('.');
*
* if(-1 == i) {i = string.length;}
* string = string.substring(0, i);
*/
The regular expression shown above will match the last full stop (.) in the string followed by zero or more characters (other than full stops). The replace method then replaces that match with an empty string. The extension is stripped, in other words.

The alternate substring/lastIndexOf approach returns the string that consists of all characters from the start of the string up to, but not including, the last full stop. The characters that follow that full stop don't matter.


bitOfArray = myArray[0];At this point, bitOfArray will be a string value.


bitOfArray.split(".gif")The split method will return an array containing two elements. The first is the portion of the string before '.gif', and the second is an empty string. The bitOfArray variable will still contain the original string, 'cheese.gif'.


bitOfArray.join("");This will throw an exception because there is no join method on the String prototype chain. Even if there was, the join method also returns a value leaving the Array object unchanged.

Mike