Spliting a var by length

hey…
id like some help with a coding problem =)
i have a var lets say ‘x’
x=“i like cheese and want to eat it everyday”
i want to split the var x by every 10’th character, assuming the 10 chracter is not in the middle of a word , then i want it to split it before that so that no words are not cut out…
ex:
x=“i like cheese and want to eat it everyday”
arr[1]="i like " 7chars causs 10th char was inside ‘cheese’ and spliting of words is not allowed
arr[2]="cheese and " 10 chars exactly , splits at space
arr[3]="want to " 8 chars 10th char inside eat … u get the idea by now i hope =)
arr[4]="eat it "
arr[5]=“everyday”
so its splitting the variable every 10th character… if the 10th chracter is a space, if it is not it backs up to the previous space and for the next array slot starts from there

hope this makes sense =)

been trying to figure this out for a while now with no luck, hoping the geniuses at kirupa can :wink:

try this code:

SeparateChunks = function(original_string, chunk_max_length){
	chunk_max_length++;
	var final_array = [];
	var position = 0;
	var length = original_string.length;
	var string_segment, end_position;
	while (position < length){
		string_segment = original_string.substr(position, chunk_max_length);
		end_position = string_segment.lastIndexOf(" ")+1;
		if (end_position <= 1) end_position = chunk_max_length;
		string_segment = original_string.substr(position, end_position);
		final_array.push(string_segment);
		position += end_position;
	}
	return final_array;
}

result = SeparateChunks("i like cheese and want to eat it everyday", 10);
trace(result); // i like ,cheese and ,want to ,eat it ,everyday

Thank you !
now just a quick follow up question =)
i c that the code places , wereever it should be broken up is there a way to make it use some less used character, there will be commas in my text from the begining
id like it to add something like ^ to all places were it should be broken
or even better “^!^” were ever its supposed to be broken to make sure the break symbols wont occur anywere else

and then comes another question
how do i put the var with the ‘break’ symbols into an array , were each slot gets 1 piece of it offcourse, and at the same time remove all the break symbols such as “^!^”

no, it doesnt place “,” anywhere, it makes an array, just like you wanted. Look at the code again. See where it says “return final_array;” ? That means its an array! You just see “,” in the output window when tracing arrays. If you want to join the array elements with “^!^” use Array.join()

ahh … i was looking at it wrong then =) … i tried to output result[1] but it still just shows the commas …
how do i show each part of it then?

nvm , got it , just couldent do result[1] in the var for the dynamic text boxes… had to do sumthing like
x1=result[1]
x2=result[2]
first in the script …

thanks very much for help =)