View Full Version : regex and javascript arrays

08-03-2006, 05:38 AM
I'm having a peculiar problem, but probably simple for the right person...I have the following code:




<script type="text/javascript">

var data = "^^^^^randallj";

regex = /\^\^\^\^\^/g;
parts = data.split(regex);

document.write("parts[0] = "+parts[0]+"<br><br>parts[1] = "+parts[1]);



I noticed that in IE, I get this output:

parts[0] = randallj

parts[1] = undefined

but in Firefox, I get this output:

parts[0] =

parts[1] = randallj

Why is this, and what am I missing here? And most importantly, how do I fix this problem? I would like the array to be filled as it is in Firefox.

Thank you.

08-03-2006, 08:32 AM
You don't need the RegExp to split a string, as the split() method does a global search anyway:

parts = data.split('^^^^^');

08-03-2006, 08:06 PM
Thanks, that does fix the problem I was having....

But I'm still wondering why when the regex is used, the arrays are filled differently in different browsers...it seems like these 2 lines of code should return the same results:

var data = "^^^^^randallj";

regex = /\^\^\^\^\^/g;
parts = data.split(regex);


var data = "^^^^^randallj";

parts = data.split('^^^^^');

08-03-2006, 09:54 PM
a Reg Exp is not exactly a string. Or in fact is more than that... Anyway, split() method do not use RegExp. It does not need. It is simply a method that does not fixed with RegExp.