Problems with split()


I’m having a problem with the split function in js…never had this before and i’m baffled.

consider this code:


used with this text:

3rd Floor,Ballaytyne Hoose,84 Acatemy Street,Invtiness,IP9 0LU

The first alert gives me ‘string’ - so i know i’m working with a string.

Then i do a split on the comma.

Then the next alert gives me back 62 or something…basically the length of all the chars in the string.

I was expecting the string to be broken on the comma…why isn’t this happending?

alert(innerText[0]) gives me back ‘3’ so i klnow the split is splitting on every charatcer.

Why is this??

I’m going mad !!!

A string is a primitive type in JavaScript – it cannot be mutated in-place by its methods. When you call split(), the string (innerText) is left alone. A new array is returned from the split() function, so to have access to the array you’ll need to assign it to a variable:

var splitInnerText = innerText.split(',');

Also, [0] simply returns the first character in a string (‘foo’[0] === ‘f’). Note that this is not standardized behaviour, and doesn’t work in all browsers.

Ahh…what an idiot. I’ve literally used this a million times before…after a long day i didn’t even think to do that…I was just thinking it’s a string…this is correct…i’m trying to split a string…WHY WON’T IT WORK!!!

Many thanks JimmyP…you’ve solved my problem and put my mind at rest