Jump to content

an almost-complete wordwrap function


sw45acp

Recommended Posts

Hi, I wish to write a function to word-wrap a string to a certain width, and if a word breaks that width, I want it to reverse course and find the nearest space, so that way no words are broken apart. I've gotten far, I just can't figure out how to go backwards with it.

function wordWrap(string,width) {
var output = '';
for (var i = 0; i < string.length; i ++) {
	output += string.substr(i,1);
	if (i == width) {
		if (string.charAt(i) == ' ' ) {
			output += '<br />';
		}else{
			//go backwards and try to find a space
			//HOW??
		}
	}
}
alert(output);
}

 

Thank you for your help.

Link to comment
https://forums.phpfreaks.com/topic/203478-an-almost-complete-wordwrap-function/
Share on other sites

I've gotten a little bit farther...

function wordWrap(string,width) {
var output = '';
for (var i = 0; i < string.length; i ++) {
	output += string.substr(i,1);
	if (i == width) {
		if (string.charAt(i) == ' ' ) {
			output += '<br />';
		}else{
			//takes the current position and pulls out everything before it
			var part = string.substr(0,i);
			//from that string, pulls out the last space
			var pos = part.lastIndexOf(' ');
			//show it
			alert(pos);
			//how to insert it into that position?
		}
	}
}
alert(output);
}

var stuff = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen";
wordWrap(stuff,20);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.