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
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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.