...

View Full Version : Dividing a String into Sets



nolachrymose
10-29-2003, 12:17 AM
I was wondering if someone could create a code to divide strings into array elements based on a parameter of the amount of characters in each element? (I've tried many different ways, but none are successful.) For instance, if I had a string with the value "foobar" and I wanted to divide it into sets of three characters in an array, I would get a result of myArray[0] = "foo" and myArray[1] = "bar".

Any help is greatly appreciated! Thanks! :)

liorean
10-29-2003, 12:48 AM
function fnStringSplit(s){
var
i,
a=s.split(/(.{0,3})/);
i=a.length;
while(i-->0)
if(a[i]=='')
a.splice(i,1);
return a;
}


fnStringSplit('foobar'); // => foo,bar
fnStringSplit('1foobar'); // => 1fo,oba,r
fnStringSplit('12foobar'); // => 12f,oob,ar
fnStringSplit('123foobar'); // => 123,foo,bar

That's given the browser supports full regex and Array.splice. Array.splice can be repaired, but not the regex. If you want it to search from the end of the string, that's far more complicated. The easiest thing to do is to split the string into an array of single characters, reverse it, join it, execute the regex, and split/reverse/join all the resulting parts afterward.

liorean
10-29-2003, 12:50 AM
Hmm, if you want to supply the number of characters as a parameter you must use the RegExp constructor instead of the literal I used.

/(.{0,3})/ --> new RegExp('(.{0,'+n+'})')

COBOLdinosaur
10-29-2003, 12:56 AM
str='foobar';
setsize=3;
arr= new Array();
for (i=0;i<str.length;i+=3)
{
j=arr.length;
arr[j]=str.substring(i,i+setsize);
}

mordred
10-29-2003, 01:28 AM
For the sake of completeness, you can also use a global match() on the string:



String.prototype.makeSet = function(num) {
return this.match(new RegExp('.{1,' + num + '}', 'g')) || new Array();
}


Hmh, not really a winner in readability. The "|| new Array()" is necessary to return an array if no matches were found, as it would be the case for an empty string, which would return null.

nolachrymose
10-29-2003, 02:51 AM
Thank you all! I got it going now. ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum